【发布时间】:2017-06-19 15:48:06
【问题描述】:
我一步一步地查看了这个函数,在我看来,它应该避免调用sortedCoins(0-1),只使用sortedCoins(0) 并在y == -1 时终止,但不知何故它没有。为什么?
def countChange(amount: Int, coins: List[Int]): Int = {
var x = coins.length
var y = x
val sortedCoins = coins.sortWith(_ < _)
def cc(amount: Int, x: Int): Int = {
y -= 1
if (amount == 0) 1
else if (y == 0) cc(amount - x, sortedCoins(y))
else if (amount < 0 || y == -1) 0
else cc(amount, sortedCoins(y - 1)) + cc(amount - x, sortedCoins(y))
}
cc(amount, x)
}
【问题讨论】:
-
我建议学习如何使用调试器逐行执行程序。这对您非常有用(对于这个和未来的问题)。令人惊讶的是,提问者可以通过这种方式更轻松地为自己解决多少问题
-
在另一张纸条上,当我看到
coins: List[Int]它可能应该是coins: List[Coin]时,它让我很生气。至少你应该使用一个值类,但实际上你应该使用 ADT(代数数据类型) -
这是作业题吗?好像我在 Coursera 课程中看到过这个......
-
是的,countChange函数的这种定义签名有一个问题需要解决。已经与这个谜题战斗了 10 个小时
标签: scala list exception indexoutofboundsexception