• Leetode-891-子序列宽度之和


    在这里插入图片描述

    1、数学

    因为我们需要求得是子序列的宽度之和,我们可以先确定不同宽度对应的子序列的个数,而后将其相加即可。我们可以首先在子序列中固定最大值和最小值,此时在剩余的 n − 2 n-2 n2个数中我们可以依次选择0或1或2一直到 n − 2 n-2 n2个,根据组合数公式: C n 0 + C n 1 + C n 2 + ⋯ + C n n = 2 n C_{n}^{0} +C_{n}^{1}+C_{n}^{2}+\cdots+C_{n}^{n}=2^n Cn0+Cn1+Cn2++Cnn=2n我们可以确定当前的宽度对应了 2 n − 2 2^{n-2} 2n2个子序列。接着我们可以在子序列中固定第二个最大值和最小值,同理,此时在剩余的 n − 2 n-2 n2个数中我们可以依次选择0或1或2一直到 n − 3 n-3 n3个。依次类推固定了最小值的子序列共有 ( m a x − m i n ) × 2 n − 2 + ( m a x 2 − m i n ) × 2 n − 3 + ⋯ + ( m i n 2 − m i n ) × 2 1 (max-min)\times2^{n-2}+(max2-min)\times2^{n-3}+\cdots+(min2-min)\times2^1 (maxmin)×2n2+(max2min)×2n3++(min2min)×21。我们可以按照以上规律依次求出每一个宽度对应的子序列数,我们最终将其相加后可以得到如下式子: ( m a x − m i n ) × 2 n − 2 + ( m a x + m a x 2 − m i n 2 − m i n ) × 2 n − 3 + ⋯ + ( m a x + m a x 2 − m i n 2 − m i n ) × 2 1 + ( m a x − m i n ) × 2 0 (max-min)\times2^{n-2}+(max+max2-min2-min)\times2^{n-3}+\cdots+(max+max2-min2-min)\times2^{1}+(max-min)\times2^{0} (maxmin)×2n2+(max+max2min2min)×2n3++(max+max2min2min)×21+(maxmin)×20。我们对上述式子求和即可。

    class Solution {
    public:
        long long mod = 1e9 + 7;
    
        long pow(long x, int n) {
            long res = 1L;
            for (; n; n /= 2) {
                if (n % 2) res = res * x % mod;
                x = x * x % mod;
            }
            return res;
        }
    
        int sumSubseqWidths(vector<int> &nums) {
            int n = nums.size();
            long long res = 0, sum = 0;
            sort(nums.begin(), nums.end());
            for (int i = 0; i < n - 1; ++i) {
                sum += nums[n - 1 - i] - nums[i];
                res = (long long) (res + sum * pow(2L, i)) % mod;
            }
            return res;
        }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
  • 相关阅读:
    【WLAN】Android 13 WIFI 选网机制--NetworkNominator 解读
    C++ 判断闰年 & 洛谷习题P5737题解
    【LeetCode】按公因数计算最大组件大小 [H](并查集)
    Ansible自动化运维
    Vue的进阶使用--模板语法应用拓展(表单及组件通信)
    创意涌动:CSDN·大学生博主14天创作挑战赛·第二期,正式开启报名!
    ​LeetCode解法汇总2678. 老人的数目
    Unity ab包加载文本 puerts 自定义loader
    《玩转Git三剑客》
    网络爬虫——urllib(4)文末好书推荐
  • 原文地址:https://blog.csdn.net/weixin_43825194/article/details/127931630