【发布时间】:2019-07-28 21:45:18
【问题描述】:
我正在开发一个函数,它使用递归调用将给定的输入分解为面额。
在每一步都递归成两个变体:
- 继续使用当前硬币:将其添加到列表中并递归。
- 切换到下一个硬币:增加硬币 pos 并递归。
除了在剩余 == 0 时打印出列表中捕获的面额组合之外,我还打算捕获该列表的值并从函数中返回它。
代码如下:
static final int[] DENOMINATIONS = {9,5,3};
private static void change(int remaining, List<Integer> coins, int pos)
if (remaining == 0) {
// This correctly prints the desired output.
// I want to return that exact value from the function.
System.out.println(coins);
} else {
if (remaining >= DENOMINATIONS[pos]) {
coins.add(DENOMINATIONS[pos]);
another.addAll(coins);
change(remaining - DENOMINATIONS[pos], coins, pos);
coins.remove(coins.size() - 1);
}
if (pos + 1 < DENOMINATIONS.length) {
change(remaining, coins, pos + 1);
}
}
}
public static List<Integer> denominations(int amount) {
List<Integer> result = new ArrayList<Integer>();
List<Integer> another = new ArrayList<Integer>();
change(amount, result, another ,0);
System.out.println(another.size());
return another;
}
public static void main(String[] args) {
List<Integer> list = denominations(13);
System.out.println(list);
}
输出:[5,5,3]
【问题讨论】:
-
这是基于 SICP 计数变化的例子吗?
-
我想是的。
标签: java list algorithm recursion arraylist