I went step by step looking at this function and it seems to me that it should avoid calling sortedCoins(0-1)
by using only sortedCoins(0)
and terminating when y == -1
, but somehow it doesn't. Why?
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)
}