✔ 最佳答案
輸出的時候以每個小朋友得到幾顆糖果來思考,記得要滿足每個小朋友至少有一顆的條件,而且需要注意糖果的總數是固定的N顆。
可以先從簡單的狀況來思考:
C = 3, N = 4
1 1 2
1 2 1
2 1 1
2012-11-15 17:53:17 補充:
相同物排列可以用遞迴寫出來,所以我不覺的邏輯上會有困難。數字很大的話...應該只需要擔心使用了遞迴可能會讓stack爆掉~~
2012-11-19 10:07:38 補充:
如果說執行上較慢的話可以試著把遞迴改成迴圈。
迴圈的執行速度上較快,但缺點是由遞迴改成迴圈會不容易閱讀。
下面是我自己改的可以參考看看:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MIN_CANDY_PER_CHILD 1
struct child{
int initialized;
int candy;
};
void show_child_candy(struct child* aChild, int num)
{
int i;
for(i = 0;i < num;i++){
printf("%d ", aChild[i].candy);
}
printf("\n");
}
int candy_of_child(int C, int N)
{
int child_idx = 0, candy_left;
struct child* child;
if(C * MIN_CANDY_PER_CHILD > N){
printf("Can't meet condition: each child has %d candy(s).", MIN_CANDY_PER_CHILD);
return -1;
}
child = (struct child *)malloc(sizeof(struct child) * C);
if(child == NULL){
printf("Not enough memory\n");
}
memset(child, 0, sizeof(struct child) * C);
for(candy_left = N;child[0].candy <= N;){
if(child[child_idx].initialized == 0){
child[child_idx].candy = MIN_CANDY_PER_CHILD;
child[child_idx].initialized = 1;
}else{
/* back from recursive */
candy_left += child[child_idx].candy;
child[child_idx].candy++;
}
if(child_idx == C - 1){
/* last child */
if(candy_left >= MIN_CANDY_PER_CHILD){
child[child_idx].candy = candy_left;
show_child_candy(child, C);
}
/* return */
child[child_idx--].initialized = 0;
}else{
if(child[child_idx].candy <= candy_left){
candy_left -= child[child_idx++].candy;
}else{
/* return */
child[child_idx--].initialized = 0;
}
}
}
free(child);
return 0;
}
int main(int argc, char *argv[])
{
candy_of_child(6, 10);
return(0);
}