找出k個數相加得n的所有組合
阿新 • • 發佈:2018-02-24
gpo caller define 所有 ack nbsp not != array
Find all possible combinations of k positive numbers that add up to a number n,each combination should be a unique set of numbers.
1 /** 2 * Return an array of arrays of size *returnSize. 3 * The sizes of the arrays are returned as *columnSizes array. 4 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().5 */ 6 #define SIZE 600 7 int** function(int k, int n, int** columnSizes, int* returnSize) { 8 int **ret=(int**)malloc(sizeof(int*)*SIZE); 9 int *sum=(int*)calloc(SIZE,sizeof(int)); 10 int *countArray=(int*)calloc(SIZE,sizeof(int)); 11 int temp_n=n; 12 int count=0; 13 int temp=1; 14 int temp_k=0; 15 int back=0; 16 *returnSize=0; 17 if(k==1){ 18 *returnSize=1; 19 columnSizes[0]=(int*)malloc(sizeof(int)); 20 columnSizes[0][0]=1; 21 ret[0]=(int*)malloc(sizeof(int)); 22 ret[0][0]=n; 23 return ret; 24 } 25 for(int i=0;i<SIZE;i++){ 26 ret[i]=(int*)calloc(k,sizeof(int)); 27 } 28 while(temp*k+(k-1)*k/2<=n){ 29 ret[(*returnSize)][0]=temp; 30 countArray[(*returnSize)]++; 31 sum[(*returnSize)]=temp; 32 temp++; 33 (*returnSize)++; 34 } 35 while(ret[count][0]!=0){ 36 temp=ret[count][countArray[count]-1]+1; 37 temp_k=k-countArray[count]; 38 while(temp*temp_k+(temp_k-1)*temp_k/2<=(n- sum[count])){ 39 if(temp_k==1){ 40 ret[count][countArray[count]]=n- sum[count]; 41 break; 42 } 43 ret[count][countArray[count]]=temp; 44 back=sum[count]; 45 sum[count]=sum[count]+temp; 46 countArray[count]++; 47 temp++; 48 while(temp*temp_k+(temp_k-1)*temp_k/2<=(n- sum[count])){ 49 for(int i=0;i<countArray[count]-1;i++){ 50 ret[(*returnSize)][i]=ret[count][i]; 51 } 52 ret[(*returnSize)][countArray[count]-1]=temp; 53 countArray[(*returnSize)]=countArray[count]; 54 sum[(*returnSize)]=back+temp; 55 temp++; 56 (*returnSize)++; 57 } 58 temp=ret[count][countArray[count]-1]+1; 59 temp_k=k-countArray[count]; 60 } 61 count++; 62 } 63 columnSizes[0]=(int*)malloc(sizeof(int)*(*returnSize)); 64 for(int i=0;i<(*returnSize);i++){ 65 columnSizes[0][i]=k; 66 } 67 return ret; 68 }
找出k個數相加得n的所有組合