c - find all the possible combination of coins, implementing by recursion -
solve problem recursion:
using 3 type coins include 1 yuan, 2 yuan , 5 yuan, plus 10 yuan, how many combinations?
the following 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 128 system("pause"); return 0; }
what's error of recursion algorithm or what's right code ?
question supplement :
1. (5,2,2,1) , (2,5,2,1) should counted 1 combination .
2. following code of 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 10 }
your code counting number of permutations add 10. want combinations. means (5,2,2,1) , (2,5,2,1) should counted 1 combination.
in case, answer should 10: (5,5), (5,2,2,1), (5,2,1,1,1), (5,1,..1), (2,2,2,2,2), (2,2,2,2,1,1), (2,2,2,1,1,1,1), (2,2,1,..1), (2,1,..1), , (1,..1).
try code:
int coinnum(int num, int *coins){ if (num == 0) return 1; if (num < 0 || !*coins) return 0; return coinnum(num - *coins, coins) + coinnum(num, coins+1); } int main(){ int coins[] = {5,2,1,0}; // don't forget 0 or program won't end int num=coinnum(10,coins); printf("%d\n",num); // result 10 system("pause"); return 0; }
the code above tries combinations until sum equals or exceeds desired sum. note not efficient algorithm solve problem, simple one. better algorithms, should @ computer science stack exchange.
Comments
Post a Comment