长度为n的数组,应该有1<<n个子序列。排序之后不会改变子序列个数。对于一个数,左边的数组构成了让他变成最大数的子序列,那么它为最大数的个数为1<<left个数。同理右边个数为它为最少数个数。
对于A[i] * ((1<<left) - (1<<right)) 求和
class Solution {
public:
int sumSubseqWidths(vector<int>& A) {
long ans = 0;
const long mod = 1000000007;
sort(A.begin(), A.end());
long *dp = new long[A.size()];
dp[0] = 1;
for (int i = 1; i < A.size(); ++i)
dp[i] = (dp[i - 1] << 1) % mod;
for (int i = 0; i < A.size(); i++)
{
long left = i;
long right = A.size() - i - 1;
ans += (dp[left] - dp[right]) * A[i];
ans = (ans + mod) % mod;
}
delete [] dp;
return ans;
}
};
/*
0 1
1 1
2 3
3 7
*/