找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
说明:
所有数字都是正整数。 解集不能包含重复的组合。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
int **ret = NULL;
int k_temp = 0;
int n_temp = 0;
int retSize = 0;
int *retColSize = NULL;
int *arrays = NULL;
void Backtrack(int count,int index)
{
if(count == k_temp)
{
int *temp = (int*)malloc(sizeof(int) * k_temp);
memcpy(temp, arrays, sizeof(int) * k_temp);
ret[retSize] = temp;
retColSize[retSize++] = k_temp;
return;
}
int num = 0;
for(int i = index; i < 10; i++) //组合问题,不需要重复的排列
{
arrays[count] = i;
if(count == k_temp-1) //判断是否和为n
{
for(int j = 0; j < k_temp; j++)
{
num += arrays[j];
}
if(num != n_temp)
{
num = 0;
continue;
}
}
Backtrack(count+1, i+1);
arrays[count] = 0;
}
}
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int** combinationSum3(int k, int n, int* returnSize, int** returnColumnSizes){
ret = (int **)malloc(sizeof(int*) * 1000);
k_temp = k;
n_temp = n;
retSize = 0;
retColSize = (int *)malloc(sizeof(int) * 1000);
arrays = (int*)malloc(sizeof(int) * k_temp);
memset(arrays, 0, sizeof(int) * k_temp);
Backtrack(0,1);
free(arrays);
*returnSize = retSize;
*returnColumnSizes = retColSize;
return ret;
}