Given an infinite number of quarters (25 cents), dimes (10 cents), nickels (5 cents) and pennies (1 cent), write code to calculate the number of ways of representing n cents.
简单的DFS可以解决,书中的理解起来感觉有些复杂。不过可以放在一起对比验证 - DFS确实慢啊,大数据多半不能接受,加上一个简单的剪枝效果可以好很多,不过还是不如书上的解法快。
void makeChange(int sum, int *coins, int n, int start, int &result) {
if (sum < 0) {
return;
}
if (sum == 0) {
++result;
return;
}
for (int i = start; i < n; ++i) {
// Only one solution if coin equals to 1
if (i == n - 1) {
++result;
}
else {
makeChange(sum - coins[i], coins, n, i, result);
}
}
}
int make_change(int n, int denom){
int next_denom = 0;
switch (denom){
case 25:
next_denom = 10;
break;
case 10:
next_denom = 5;
break;
case 5:
next_denom = 1;
break;
case 1:
return 1;
}
int ways = 0;
for(int i = 0; i*denom <= n; ++i)
ways += make_change(n - i*denom, next_denom);
return ways;
}
int main(int argc, char **argv) {
int coins[] = {25, 10, 5, 1};
int result = 0;
time_t s1 = time(NULL);
makeChange(8000, coins, 4, 0, result);
double diff = difftime(time(NULL), s1);
cout << "The numbers to make change is: " << result << " and the time used is: " << diff << endl;
s1 = time(NULL);
result = make_change(8000, 25);
diff = difftime(time(NULL), s1);
cout << "The numbers to make_change is: " << result << " and the time used is: " << diff << endl;
return 0;
}