Leetcode 题解 Combinations:回溯+求排列组合

时间:2021-11-02 13:24:31

罗列出从n中取k个数的组合数组。

首先,求C(n,k)这个实现,很粗糙,溢出也不考虑,好的方法也不考虑。笨蛋。心乱,上来就写。。

另外,发现在递归中,不能申请太大的数组?貌似不是这个问题,是我自己越界了。

/**
* 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 com(int n,int k)
{
int i = ,ans=; if(k > n-k) k = n-k; for (i = n; i > n - k; i--)
ans *= i;
for (i = k; i > ; i--)
ans /= i;
return ans;
} int **ans;
int len; void back_track(int *last, int last_size, int num, int n, int k)
{
if(last_size == k)
{
int *tmp = (int*)malloc(sizeof(int)*k);
memcpy(tmp,last,k*sizeof(int));
ans[len++] = tmp;
//memcpy(ans[len],last,k*sizeof(int));
//len ++;
return;
} if(num > n) return; back_track(last,last_size,num+,n,k);
last[last_size] = num;
back_track(last,last_size + ,num + ,n,k);
}
int** combine(int n, int k, int** columnSizes, int* returnSize) {
if(k > n || n *k == ) { *returnSize = ; return NULL; } int size = com(n,k);
int *cols = (int*)malloc(size*sizeof(int)); ans = (int**)malloc(size*sizeof(int*));
len = ; for(int i = ; i < size; i ++)
{
//ans[i] = (int*)malloc(k*sizeof(int));
cols[i] = k;
} int *last = (int*)malloc(k*sizeof(int));
back_track(last,,,n,k); *columnSizes = cols;
*returnSize = len;
return ans;
}