• 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
  • 相关阅读:
    基于SSH开发学生公寓管理系统
    遗传算法的改进——跳出局部最优机制的研究(选择算子、交叉算子、变异算子的改进)
    MongoDB的复合通配符索引详解
    Python015--python常用库之turtle库(简单的入门)
    Redis自动过期机制之key的过期监听
    springcloud-网关(gateway)
    Howler.js HTML5声音引擎
    夜莺n9ev5配置pushgateway
    【Spring篇】Spring注解式开发
    C#模拟PLC设备运行
  • 原文地址:https://blog.csdn.net/weixin_43825194/article/details/127931630