一个典型的变化问题,但有点扭曲。鉴于给定的金额和面额很大,我需要提出使用RECURSION可以赚取金额的总方式。该功能的签名如下
int makeChange(int Amount, int[] Denominations)
金额 - 总金额
衡量单位 - 可用的denominatins。
它返回总路数。确保必须使用递归...
答案 0 :(得分:4)
关键的想法是要了解每个点你有两个选择:
amount
减去它时递归。该函数应返回(1)和(2)的总和。
的伪代码:
makeChange(amount,Denominations):
//stop clauses:
if (amount == 0) return 1
if (amount < 0) return 0
i <- first index of Denominations where Denominations[i] is not zero
if there is no such i (all are zero):
return 0
num1 = makeChange(amount-Denominations[i],Denominations) //recursive call, using Denominations[i]
temp <- Denominations[i]
Denominations[i] = 0
num2 = makeChange(amount,Denominations) //recursive call, not using Denominations[i] - and will never do again
Denominations[i] = temp //setting environment back to original
return num1+num2
java代码:
public static int makeChange(int amount, int[] d) {
if (amount < 0) return 0;
if (amount == 0) return 1;
int i = 0;
for (i = 0; i < d.length; i++) {
if (d[i] != 0) break;
}
if (i == d.length) return 0;
int num1 = makeChange(amount-d[i],d);
int temp = d[i];
d[i] = 0;
int num2 = makeChange(amount,d);
d[i] = temp;
return num1 + num2;
}