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

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 }

 

转载于:https://www.cnblogs.com/Blue-Keroro/p/8467449.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值