给定n个正整数,整数 k 和目标数target。
计算在n个数中找出k个数的和为目标数target的组合共有几种?
比如:{1, 2, 3, 4}, k = 2, target = 5.则有两种组合:
计算在n个数中找出k个数的和为目标数target的组合共有几种?
比如:{1, 2, 3, 4}, k = 2, target = 5.则有两种组合:
{1, 4}, {2, 3}.
int kSum(int *A, int n, int k, int target)
{
if (A == NULL || n < 0 || k < 0 || target < 0)
{
return 0;
}
int ***buf = new int **[n+1];
for (int i = 0; i < n+1; i++)
{
buf[i] = new int *[k+1];
for (int j = 0; j < k+1; j++)
{
buf[i][j] = new int[target+1];
}
}
for (int i = 0; i < n+1; i++)
{
for (int j = 0; j < k+1; j++)
{
for (int m = 0; m < target+1; m++)
{
if (j == 0 && m == 0)
{
buf[i][j][m] = 1;
}
else if (!(i == 0 || j == 0 || m == 0))
{
buf[i][j][m] = buf[i-1][j][m];
if (A[i-1] <= m)
{
buf[i][j][m] += buf[i-1][j-1][m-A[i-1]];
}
}
else
{
buf[i][j][m] = 0;
}
}
}
}
int result= buf[n][k][target];
for (int i = 0; i < n+1; i++)
{
for (int j = 0; j < k+1; j++)
{
delete buf[i][j];
}
delete buf[i];
}
delete []buf;
return result;
}