我有一个看起来像这样的scala代码
object Main {
def countChangeIter(money: Int, coins: List[Int], counter: Int): Int=
if (money == 0) 1
else if (money < 0) 0
else {
for (i <- coins.indices) {
counter = counter + countChangeIter(money - coins(i), coins.drop(i), 0)
}
return counter
}
def countChange(money: Int, coins: List[Int]): Int = countChangeIter(money, coins, 0)
}
问题在于counter = counter...
声明。如何通过旧计数器和countChangeIter返回的总和来实现计数器的变化?
答案 0 :(得分:2)
您可以这样做:
object Main {
def countChangeIter(money: Int, coins: List[Int], counter: Int): Int=
if (money == 0) 1
else if (money < 0) 0
else {
var myCounter = counter
for (i <- coins.indices) {
myCounter = myCounter + countChangeIter(money - coins(i), coins.drop(i), 0)
}
return myCounter
}
def countChange(money: Int, coins: List[Int]): Int = countChangeIter(money, coins, 0)
}
请记住,如果您需要在函数式编程设置中执行此操作,那么代码的结构可能有问题。