# [cc150] 硬币问题

Given an infinite number of quarters (25 cents), dimes (10 cents), nickels (5 cents) and pennies (1 cent), find how many ways to represent n cents.

num_quarters = 0 的是一类，

num_quarters = 1 的是一类，

。。。

num_quarters = 4 的是一类

num_quarters = 0 的子集中，num_dimes = 0的是一类，num_dimes = 1的是一类，。。。

public int makeChange(int amount) {
int[] denoms = {25, 10, 5, 1};
return makeChange(amount, denoms, 0);
}

public int makeChange(int amount, int[] denoms, int index) {
if(index == denoms.length - 1)
return 1;

int ways = 0;
for(int i = 0; i <= amount / denoms[index]; ++i){
ways += makeChange(amount - i * denoms[index], denoms, index+1);
}
return ways;
}

int makeChange(int n){
int[] denoms = {25, 10, 5, 1};
int[][] map = new int[n+1][denoms.length];
return makeChange(n, denoms, 0, map);
}

int makeChange(int amount, int[] denoms, int index, int[][] map){
if(map[amount][index] > 0){
return map[amount][index];
}

if(index >= denoms.length - 1)
return 1;

int denomAmount = denoms[index];
int ways = 0;
for(int i = 0; i * denomAmount <= amount; i++){
int amountRemaining = amount - i * denomAmount;
ways += makeChange(amountRemaining, denoms, index +1 , map);
}

map[amount][index] = ways;
return ways;
}

posted @ 2014-06-09 05:11  门对夕阳  阅读(479)  评论(0编辑  收藏  举报