【发布时间】:2020-02-12 21:57:19
【问题描述】:
对于这个问题,我必须编写一个方法,当用户以便士输入金额时,我必须以字符串格式输出所有可能的硬币、镍和便士组合。我只能使用递归,不能使用任何类型的循环或集合(即数组、列表、堆栈等)。这段代码应该可以工作,但由于某种原因它没有输出所有组合,它缺少:“0d 3n 7p”和“0d 0n 17p”输出。
package Assignement02;
public class Coins {
public static String ways (int money) {
System.out.println("Enter an amount in cents:");
System.out.println(money);
System.out.println("This amount can be changed in the following ways:");
if(money == 0) {
return "there are no ways to change that amount";
} else {
return waysHelper(0, 0, 0, money);
}
}
public static String waysHelper(int countd, int countn, int countp, int money) {
if(money >= 10) {
countd++;
return waysHelper(countd, countn, countp, money - 10);
} else if (money >= 5) {
countn++;
return waysHelper(countd, countn, countp, money - 5);
} else {
String s = " " + countd + "d, " + countn + "n, " + money + "p";
int orig = 10*countd + 5*countn + money;
return counterHelper(orig, countd, countn, money, s);
}
}
public static String counterHelper(int money, int countd, int countn, int countp, String s) {
if(countp == money) {
s = s + s + "\n " + countd + "d, " + countn + "n, " + countp + "p";
}
if(countd > 0) {
if(countn > 0) {
countn--;
countp = countp + 5;
s = s + "\n " + countd + "d, " + countn + "n, " + countp + "p";
counterHelper(money, countd, countn, countp, s);
}
countd--;
countn = countn + 2;
s = s + "\n " + countd + "d, " + countn + "n, " + countp + "p";
counterHelper(money, countd, countn, countp, s);
}
if(countn > 0) {
countn--;
countp = countp + 5;
s = s + "\n " + countd + "d, " + countn + "n, " + countp + "p";
counterHelper(money, countd, countn, countp, s);
}
if(countn > 0) {
countn--;
countp = countp + 5;
s = s + "\n " + countd + "d, " + countn + "n, " + countp + "p";
counterHelper(money, countd, countn, countp, s);
}
return s;
}
public static void main(String[] args) {
System.out.print(ways(17));
}
}
输出:
输入以美分为单位的金额: 17 可以通过以下方式更改此金额: 1d、1n、2p 1d、0n、7p 0d、2n、7p 0d、1n、12p 0d、0n、17p
【问题讨论】:
标签: java recursion methods recursive-query