77. 组合
解
/**
* 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().
*/
void func(int n, int k, int *returnSize, int **array, int *ans, int ansidx, int idx) {
if (n - idx < k - ansidx-1) return;
if (ansidx == k) {
for (int i = 0; i < k; i++) {
array[(*returnSize)][i] = ans[i];
}
(*returnSize)++;
return;
}
for (int i = idx; i <= n; i++) {
ans[ansidx++] = i;
func(n, k, returnSize, array, ans, ansidx, i+1);
ansidx--;
}
}
int** combine(int n, int k, int* returnSize, int** returnColumnSizes) {
int **array = (int **)malloc(sizeof(int *) * 200001);
int *ans = (int *)malloc(sizeof(int) * k);
*returnSize = 0;
for (int i = 0; i < 200001; i++) {
array[i] = (int *)malloc(sizeof(int) * k);
}
func(n, k, returnSize, array, ans, 0, 1);
*returnColumnSizes = (int *)malloc(sizeof(int) * (*returnSize));
for (int i = 0; i < *returnSize; i++) {
(*returnColumnSizes)[i] = k;
}
return array;
}
注意数组大小, 会有内存限制