SCALA Exercise 3: Counting Change
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 denomination 1 and 2: 1+1+1+1, 1+1+2, 2+2.
Do this exercise by implementing the countChange function inMain.scala. This function takes an amount to change, and a list of unique denominations for the coins. Its signature is as follows:
Once again, you can make use of functions isEmpty, head and tail on the list of integers coins.
Hint: Think of the degenerate cases. How many ways can you give change for 0 CHF(swiss money)? How many ways can you give change for >0 CHF, if you have no coins?
def countChange(money: Int, coins: List[Int]): Int = {
if(money == 0)
1
else if(money > 0 && !coins.isEmpty)
countChange(money - coins.head, coins) + countChange(money, coins.tail)
else
0
}
这个Hint给出了基本情况,即
1.money>0且没有coins的情况
2.money=0的情况
以以上两个情况为出口,写递归。
recursion的两种情况:
1.countChange(money - coins.head, coins)
要么使用第一种面额的钱来凑money2.countChange(money, coins.tail)要么用其它面额的钱来凑money
总的情况为上述两种情况相加。对于money=4,coins为[1,2]的情况,递归的过程基本是这样的:1,1,1,11,1,1,2 减完为为负数,排除1,1,21,2,2 剪完为负数,排除2,2
countChange(money - coins.head, coins)
will exhaust all combinations subtracting the first coin from the money, whilecountChange(money, coins.tail)
exhausts all combinations using all other coins only. They are added together, since + is synonymous with the logical OR operator. – rkenmi May 6 '17 at 6:01