题目描述:
给定两个整数 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