给定一组 n 个元素,求最大为 k 的子集的乘积之和(k 是另一个整数)。
n 的范围在 1000 秒内,所以我需要比指数时间复杂度更快的东西。
我觉得这个问题可以使用多项式 FFT 解决,但我不确定。另外,请查看https://math.stackexchange.com/questions/786183/sum-of-multiplication-of-all-combination-of-m-element-from-an-array-of-n-element/788655 #788655
例如 :
: {1, 2, 3, 4, 5}
k = 2
那么答案将是
1 + 2 + 3 + 4 + 5 + 1*2 + 1*3 + 1*4 + 1*5 + 2*3 + 2*4 + 2*5 + 3*4 + 3*5
非常感谢伪代码或关于如何更接近解决方案的一些指针。
令 DP[i][j]:大小正好为 j 的子集的乘积之和,其中只包含第 [1~i] 个元素。
然后 DP[i][j] = DP[i-1][j] + DP[i-1][j-1] * arr[i]
现在你可以在时间复杂度 O(NK) 上解决它。
== 编辑 ==
这是一个简单的代码。
int arr[1002]; /// The array where number is located
int DP[1002][1002];
int ans=0; /// final answer
DP[0][0] = 1;
for(int i=1; i<=n; i++){
DP[i][0] = 1;
for(int j=1; j<=i && j<=k; j++){
DP[i][j] = DP[i-1][j] + DP[i-1][j-1] * arr[i];
}
}
for(int i=1; i<=k; i++) ans+=DP[n][i];
Run Code Online (Sandbox Code Playgroud)