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