码迷,mamicode.com
首页 > 其他好文 > 详细

找出k个数相加得n的所有组合

时间:2018-02-24 20:45:26      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:free   ++   count   turned   and   tar   ==   span   组合   

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的所有组合

标签:free   ++   count   turned   and   tar   ==   span   组合   

原文地址:https://www.cnblogs.com/Blue-Keroro/p/8467449.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!