使用递归的Scala中的硬币变化算法 [英] coin change algorithm in scala using recursion
本文介绍了使用递归的Scala中的硬币变化算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用递归在 Scala 中编写硬币找零问题.我写的代码如下.
I am trying to program the coin change problem in Scala using recursion. The code that i have written is as follows.
def countChange(money: Int, coins: List[Int]): Int = {
def ways(change: List[Int], size: Int, capacity: Int): Int = {
if(capacity == 0) 1
if((capacity < 0) || (size <= 0)) 0
//println and readLine to check and control each recursive call.
println("calling ways(",change, change.length-1, capacity,") + ways(",change, change.length, capacity - change(change.length - 1),")")
readLine()
//
ways(change, change.length-1, capacity) + ways(change, change.length, capacity - change(change.length - 1))
}
ways(coins, coins.length, money)
}
在运行代码时,它不会终止并继续调用第一个递归调用.我哪里出错了?
On running the code, it does not terminate and keeps on calling the first recursive call. Where am I going wrong?
推荐答案
简单地声明一个值不会让 Scala 返回它;您要么需要明确的回报,要么必须是最后一项声明.因此:
Simply stating a value does not make Scala return it; you either need an explicit return, or it has to be the last item stated. Thus:
if (capacity == 0) return 1
或
if (capacity == 0) 1
else if (...)
else { ... }
这篇关于使用递归的Scala中的硬币变化算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文