原题链接
The width of a sequence is the difference between the maximum and minimum elements in the sequence.
Given an array of integers nums
, return the sum of the widths of all the non-empty subsequences of nums
. Since the answer may be very large, return it modulo 109 + 7
.
A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7]
is a subsequence of the array [0,3,1,6,2,2,7]
.
这是道数学题,求所有子序列的最大值和最小值之差(宽度)的和
最暴力的解法就是排列组合,看看序列长度计算一下复杂度100000!,那还是歇着吧
子序列的最大值和最小值是跟序列的顺序无关,这个序列的最大值和最小值如果固定作为一组,那么中间值的个数变化并不会影响序列的宽度,将最大值和最小值一样的序列的个数乘以宽度就得到了这组的宽度和
将所有最大值和最小值组的宽度相加,就是总宽度和
最大和最小值的组数就是排序后nums[i],nums[j]之间选任意个数出来的组合,个数为2^(j-i-1)个(tms[j-i-1]),这里可以去查询排列组合的知识
因此有第一版代码:
class Solution {
public:
int sumSubseqWidths(vector<int>& nums) {
sort(nums.begin(), nums.end());
long tms[100000] = {1};
int md = (1e9)+7,rst = 0;
for (int i = 1; i<= nums.size(); i++) {
tms[i] = (tms[i-1] <<1)%md;
}
for (int i = 0; i< nums.size(); i++) {
for (int j = i+1; j<nums.size(); j++) {
if(nums[i] < nums[j]) {
rst = (tms[j -i -1] * (nums[j] -nums[i]) + rst)%md;
}
}
}
return rst;
}
};
所有case都能过,但是超时了。。。。
明显sort是n*log(n),需要优化的是双层嵌套循环
看双层循环的第二层,如果当前点是j-1,那么从0到j-1的所有宽度和为
sm(j-1) = tms[j-2]*(nums[j-1] - nums[0]) +.........+tms[0]*(nums[j-1] - nums[j-2)
同理
sm(j) = tms[j-1]*(nums[j] - nums[0]) +.........+tms[0]*(nums[j] - nums[j-1)
这里是为了求sm(j-1)与sm(j)的递推关系,nums[j] - nums[0]拆成
nums[j] - nums[0] = nums[j] - nums[j-1] + nums[j-1] - nums[0]
带入sm(j)等式,将nums[j] - nums[j-1]提出来:
sm(j) = 2*(sm[j-1] + (tms[j-1] -1) * (nums[j] - nums[j-1])) + (nums[j] - nums[j-1])
这就求得了sm(j)和sm(j-1)的关系式,将sm从1🏠到length
就得出答案了,将j替换成i:
class Solution {
public:
int sumSubseqWidths(vector<int>& nums) {
sort(nums.begin(), nums.end());
long tms = 1 ,md = (1e9)+7,rst = 0,sm = 0;
for (int i = 1; i< nums.size(); i++) {
sm = (((tms -1) *(nums[i] - nums[i-1]) + sm)<<1)%md +nums[i] - nums[i-1];
rst = (rst +sm) %md;
tms = (tms <<1)%md;
}
return rst;
}
};