一个朋友正在做一个在线 Scala 课程并分享了这个。
# Write a recursive function that counts how many different ways you can make
# change for an amount, given a list of coin denominations. For example, there
# are 3 ways to give change for 4 if you have coins with denomiation 1 and 2:
# 1+1+1+1, 1+1+2, 2+2.
如果您正在参加并仍在研究解决方案,请不要阅读此内容!
(免责声明:即使我的 Python 解决方案可能是错误的,如果你在课程中,我不想影响你的想法,不管是哪种方式!我想这是产生学习的想法,而不仅仅是“解决”...)
那一边...
我想我会在 Python 中尝试一下,因为我没有 Scala 印章(我自己不在课程上,只是对学习 Python 和 Java 感兴趣,欢迎“练习”练习)。
这是我的解决方案,我想使用尽可能紧凑的符号将其移植到 Java:
def show_change(money, coins, total, combo):
if total == money:
print combo, '=', money
return 1
if total > money or len(coins) == 0:
return 0
c = coins[0]
return (show_change(money, coins, total + c, combo + [c]) +
show_change(money, coins[1:], total, combo))
def make_change(money, coins):
if money == 0 or len(coins) == 0:
return 0
return show_change(money, list(set(coins)), 0, [])
def main():
print make_change(4, [2, 1])
if __name__ == '__main__':
main()
问题
- 如果有帮助,我可以在 Java 中使上述内容变得多么紧凑,允许使用 JDK 外部的库?
我尝试自己进行移植,但它变得非常冗长,我认为通常的“必须有更好的方法来做到这一点”!
这是我的尝试:
import java.util.ArrayList;
import java.util.List;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
public class MakeChange {
static int makeChange(int money, int[] coins) {
if (money == 0 || coins.length == 0) {
return 0;
}
return showChange(money, Ints.asList(coins), 0, new ArrayList<Integer>());
}
static int showChange(int money, List<Integer> coins, int total,
List<Integer> combo) {
if (total == money) {
System.out.printf("%s = %d%n", combo, total);
return 1;
}
if (total > money || coins.isEmpty()) {
return 0;
}
int c = coins.get(0);
List<Integer> comboWithC = Lists.newArrayList(combo);
comboWithC.add(c);
return (showChange(money, coins, total + c, comboWithC) + showChange(money,
coins.subList(1, coins.size()), total, combo));
}
public static void main(String[] args) {
System.out.println(makeChange(4, new int[] { 1, 2 }));
}
}
具体来说,我非常不喜欢的是必须做下面的事情,只是为了传递一个附加了一个元素的列表副本:
List<Integer> comboWithC = Lists.newArrayList(combo);
comboWithC.add(c);
请向我展示 Java 的紧凑性和可读性如何。我仍然是两种语言的初学者......