代码如下,对于最糟糕的情况,28个1中找出总金额和为14的物品,不打印的情况下运行两秒完成,找出40116600种结果。
void printSum(double candidates[], int index[], int n)
{
for (int i = 0; i < n; i++)
cout << candidates[index[i]] << " ";
cout << endl;
}
void getsum_help(double target, double sum, double candidates[], int size, int index[], int n)
{
if (sum > target)
return;
if (fabs(sum-target) <= 1e-6*fabs(target))
printSum(candidates, index, n);
int starti = n==0 ? 0 : index[n-1]+1;
for (int i = starti; i < size; i++)
{
index[n] = i;
getsum_help(target, sum + candidates[i], candidates, size, index, n+1);
}
}
void getsum(double target, double candidates[], int size)
{
int *index = new int[size];
getsum_help(target, 0, candidates, size, index, 0);
delete []index;
}