版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hang404/article/details/85649196
题目描述:
给定两个整数 n 和 k,返回 1 … n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
题目解答:
方法1:回溯算法
循环加递归,记录前边存储的数字,当存储k
个即可存储在结果中。
也可以先计算出总共用多少个结果,这样就可以直接给result
申请对应大的空间。
运行时间24ms,代码如下。
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *columnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
void dfs(int*** result, int* size, int n, int k, int* use, int used, int start) {
if(used == k) {
(*size)++;
result[0] = (int**)realloc(result[0], *size * sizeof(int*));
result[0][*size - 1] = (int*)malloc(k * sizeof(int));
memcpy(result[0][*size - 1], use, k * sizeof(int));
return;
}
int i = 0;
for(i = start; i < n; i++) {
use[used] = i + 1;
dfs(result, size, n, k, use, used + 1, i + 1);
}
}
int** combine(int n, int k, int** columnSizes, int* returnSize) {
int i = 0;
int** result = NULL;
int* use = (int*)malloc(k * sizeof(int));
dfs(&result, returnSize, n, k, use, 0, 0);
columnSizes[0] = (int*)malloc(*returnSize * sizeof(int));
for(i = 0; i < *returnSize; i++)
columnSizes[0][i] = k;
free(use);
return result;
}
方法2:迭代法
也有点回溯的感觉,当后一个数字超过最大值,就对前一个数加一,然后继续重新递增下一个数字。
运行时间24ms,代码如下。
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *columnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int** combine(int n, int k, int** columnSizes, int* returnSize) {
int i = 0;
int* use = (int*)calloc(k, sizeof(int));
int** result = NULL;
while(i >= 0) {
use[i]++;
if(use[i] > n)
i--;
else if(i == k - 1) {
(*returnSize)++;
result = (int**)realloc(result, *returnSize * sizeof(int*));
result[*returnSize - 1] = (int*)malloc(k * sizeof(int));
memcpy(result[*returnSize - 1], use, k * sizeof(int));
}
else {
i++;
use[i] = use[i - 1];
}
}
columnSizes[0] = (int*)malloc(*returnSize * sizeof(int));
for(i = 0; i < *returnSize; i++)
columnSizes[0][i] = k;
free(use);
return result;
}