Solve the problem by recursion:
using three type coins include 1 yuan, 2 yuan and 5 yuan, plus to 10 yuan, how many combinations?
The following is my code :
int coinNum(int num){
if(num>=0){
if(num==0)
return 1;
else
return coinNum(num-5)+coinNum(num-2)+coinNum(num-1);
}else
return 0;
}
int main(){
int num=coinNum(10);
printf("%d\n",num);//the result is 128
system("pause");
return 0;
}
What's the error of my recursion algorithm or what's your right code ?
question supplement :
1. (5,2,2,1) and (2,5,2,1) should be counted as 1 combination .
2. the following is my code of the enumeration algorithm .
void coin(){
int i,j,k,count=0;
for(i=0;i<=10;i++)
for(j=0;j<=5;j++)
for(k=0;k<=2;k++)
if((i+2*j+5*k)==10){
count++;
printf("one yuan :%d,2 yuan :%d,5 yuan :%d\n",i,j,k);
}
printf("总方法数%d\n",count);//the result is 10
}
1 . I get the result of 10 by enumeration algorithm which i think is right , so i feel that the result of recursion ,128 ,is wrong . but i cannot detect what's the error of my code
2. (5,2,2,1) and (2,5,2,1) should be counted as 1 combination .@Scott Hunter@bolov @Pham Trung – William Jan 23 '16 at 07:48