1.题目:
给定两个整数 n 和 k,返回 1 … n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
2.代码:
/**
* 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().
*/
#define MAX 10000
/*
模拟手动找出的过程;
相当于树的深度遍历,depth为深度,即当前要存放的位置;
s作为暂时存放的数组,一直都是哪一个;
*/
void dfs(int **r,int *s,int n,int k,int depth,int start,int* returnSize){
if(depth==k){ //为k即超出了,赋值
r[*returnSize]=(int *)malloc(sizeof(int )*k);
memcpy(r[*returnSize],s,sizeof(int)*k);
(*returnSize)++;
return;
}
for(int i=start;i<n;i++){
s[depth]=i+1; //i+1保证从1开始
dfs(r,s,n,k,depth+1,i+1,returnSize);
}
}
int** combine(int n, int k, int** columnSizes, int* returnSize) {
int **r=(int **)malloc(sizeof(int *)*MAX);
int *s=(int *)malloc(sizeof(int )*k);
*returnSize=0;
dfs(r,s,n,k,0,0,returnSize);
*columnSizes=malloc(sizeof(int )*(*returnSize));
for(int i=0;i<*returnSize;i++){
(*columnSizes)[i]=k;
}
return r;
}
3.知识点:
回溯