初学scala,再学递归

原题是https://class.coursera.org/progfun-002/assignment/view?assignment_id=4 的第三题

题意就是给一个序列,代表有哪几种钱币。然后问用这些钱币组成M块钱,有多少种组合的办法(硬币可无穷的取)

这个应该算是一道简单的完全背包的问题,也可以用母函数来求解。

如果是按照C的风格,那必然是套两个for,一层从range(1,len(coins))扫硬币,一层从0-M扫背包(总钱数)。

但是这次是学习scala,那么就换了个风格来写...

一开始写的各种痛苦,最后去了人家博客上取经才终于转换了思路写出这样的代码。

首先第一个版本是这样的:

  def countChange(money: Int, coins: List[Int]): Int = {
    def count(money: Int, coins: List[Int], curValue: Int): Int = {
      if (curValue > money) 0
      if (curValue == money) 1
      else if (coins.isEmpty) 0
      else {
        var res = count(money, coins.tail, curValue)
        var add = coins.head
        while (add + curValue <= money) {
          res += count(money, coins.tail, curValue + add)
          add += coins.head
        }
        res
      }
    }
    count(money, coins, 0)
  }
提交上去,因为出现了两个变量,一个while loop,扣了0.06分。

怒改之,得到了这样的:

  def countChange(money: Int, coins: List[Int]): Int = {
    def sum(money: Int, coins: List[Int], curValue: Int, add: Int): Int = {
      if(curValue > money) 0 
      else 
      count(money, coins, curValue) + sum(money, coins, curValue + add, add)
    }
    def count(money: Int, coins: List[Int], curValue: Int): Int = {
      if (curValue == money) 1
      else if (coins.isEmpty) 0
      else {
        sum(money, coins.tail, curValue, coins.head)
      }
    }
    count(money, coins, 0)
  }

希望能有人告诉我更好的写法。。。递归什么的,我还是个纯菜鸟。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值