【发布时间】:2020-05-30 02:52:45
【问题描述】:
我正在尝试创建一个程序,该程序仅使用递归和常量内存(因此没有循环)输出所有可能的独特方式来对给定输入进行更改。
对于 25 美分的金额,它应该按以下示例格式打印出所有可能的组合:
0*25+0*10+1*5+20*1
0*25+0*10+2*5+15*1
etc..
其中 0* 是用作示例的季度数 (25)
我的程序的问题是它只打印出来:
0=0*25+0*10+0*5+25*1+
而不是其余的组合。我怀疑这是因为我弄乱了 printCombinations 和 getLargerCombinations 方法(它们基本上是模拟 for 循环的递归方法),但我不知道问题出在哪里。
这是整个代码:
public class HW {
static int[] coins = {25,10,5,1};
static int[] counts = new int[coins.length];
static void getCombinations(int[] counts, int startIndex, int totalAmount) {
if(startIndex>= coins.length) {
System.out.print(""+totalAmount+"=");
printCombinations(0);
return;
}
if(startIndex == coins.length - 1) {
if(totalAmount%coins[startIndex]==0) //good combo
{
//setting count of coins at start index
counts[startIndex] = totalAmount/coins[startIndex];
//move on to recursive calls
getCombinations(counts, startIndex + 1, 0);
}
}
else //still need to choose 0-N larger coins
{
getLargerCoins(0, totalAmount, startIndex);
}
}
//Prints out all the possible combinations of change
static void printCombinations(int i) {
if(i >= coins.length) {
System.out.print("\n");
return;
}
System.out.print("" + counts[i] + "*" + coins[i] + "+");
printCombinations(++i);
}
static void getLargerCoins(int j, int totalAmount, int startIndex) {
if(j >= totalAmount/coins[startIndex]) {
return;
}
//for every cycle in the loop, we choose an arbitray # of larger coins and proceed next
counts[startIndex] = j;
getCombinations(counts, startIndex+1, totalAmount-coins[startIndex]*j);
j++;
}
public static void main(String[] args) {
getCombinations(counts, 0, 25);
}
}
****编辑:*****
在 getLargerCoins 方法下,我只是迭代了 j++,但忘记调用 getLargerCoins 方法来继续递归。通过写作修正了这一行:
getLargerCoins(++j, totalAmount, startIndex);
运行程序时的输出:
0=0*25+0*10+0*5+25*1+
0=0*25+0*10+1*5+20*1+
0=0*25+0*10+2*5+15*1+
0=0*25+0*10+3*5+10*1+
0=0*25+0*10+4*5+5*1+
0=0*25+1*10+0*5+15*1+
0=0*25+1*10+1*5+10*1+
0=0*25+1*10+2*5+5*1+
但是,它仍然没有输出所有可能的组合
【问题讨论】:
-
你试过调试你的代码吗?
-
它不会导致意外结果,但将
counts传递给每个方法调用是没有意义的,它是一个静态类字段,无论如何都可以从所有方法访问。 -
当你第一次调用 printCombination 时,你会用你的 return 语句结束递归。
标签: java arrays algorithm performance recursion