LeetCode 891. Sum of Subsequence Widths (找规律)

本文介绍了一种解决特定算法问题的方法:计算一个整数数组所有非空子序列的宽度之和,并通过优化递归公式避免了时间限制错误。文章详细解释了如何先对数组进行排序,然后使用动态规划来高效地计算结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an array of integers A, consider all non-empty subsequences of A.

For any sequence S, let the width of S be the difference between the maximum and minimum element of S.

Return the sum of the widths of all subsequences of A.

As the answer may be very large, return the answer modulo 10^9 + 7.

Example 1:

Input: [2,1,3]
Output: 6
Explanation:
Subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].
The corresponding widths are 0, 0, 0, 1, 1, 2, 2.
The sum of these widths is 6.

Note:

  • 1 <= A.length <= 20000
  • 1 <= A[i] <= 20000

解法
由题意易得,数组的顺序是可以改变的,因此先把数组排好序在处理会简单一点。在这里插入图片描述
本来是直接计算,没有算出公式,得到了TLE,后来把递归公式给算一下,就AC了。
(还要注意溢出,因此用unsigned long long稳妥)

class Solution {
    const unsigned long long mod = 1000000007;
    unsigned long long Fn[20005]; /*Fn[i] = 2^(i-1) */
    unsigned long long Sumn[20005]; /* 2^0+2^1+...+2^n = 2^(n+1)-1 */
public:
    int sumSubseqWidths(vector<int> A) {
        sort(A.begin(), A.end());
        Fn[1] = 1;
        for(int i=2;i<=20002;i++) {
            Fn[i] = (Fn[i-1]<<1)%mod;
        }
        for(int i=0;i<=20000;i++) {
            Sumn[i] = Fn[i+2]-1;
        }

        ssize_t n = A.size();
        vector<unsigned long long> res(n+1, 0);
        unsigned long long ans = 0;
        /* native method will get TLE
        for(int i=2;i<=n;i++) {
            unsigned long long tmp = 0;
            for(int j=i-1;j>=1;j--) {
                int diff = A[i-1] - A[j-1];
                tmp += (res[j] + (Fn[j] * diff)%mod)%mod;
                tmp %= mod;
            }
            res[i] = tmp;
            ans = (ans+tmp)%mod;
        }
        */
        for(int i=2;i<=n;i++) {
            res[i] = (2*res[i-1] + Sumn[i-2]*(A[i-1]-A[i-2]))%mod;
            ans = (ans+res[i])%mod;
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值