doufei1893 2014-03-31 09:41
浏览 19
已采纳

地图和动态编程更新

The problem I am given is

A child is running up a staircase with n steps, and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs.

http://play.golang.org/p/bpjIkMm9jH

package main

import "fmt"

func CountWaysDP(n int, mm map[int]int) int {
  if n < 0 {
    return 0
  } else if n == 0 {
    return 1
  } else if mm[n] > -1 {
    return mm[n]
  } else {
    mm[n] = CountWaysDP(n-1, mm) +
      CountWaysDP(n-2, mm) +
      CountWaysDP(n-3, mm)
    return mm[n]
  }
}

func main() {
  mm := make(map[int]int)
  fmt.Println(CountWaysDP(10, mm), mm)
}

This just gives me 0 map[]. It turns out that the dynamic recursion ends at the following line:

else if mm[n] > -1

Then how would I use dynamic programming to solve this problem? This is exactly the same solution as in Cracking the coding interview....

  • 写回答

3条回答 默认 最新

  • douyong1885 2014-03-31 09:54
    关注

    You need to compare with 0:

    else if mm[n] > 0
    

    map returns 0 when getting values for non existing keys.

    You can also use an array/slice instead of map as you know that the map keys are always from 1 to N

    You can solve this without recursion as well:

    package main
    
    import "fmt"
    
    func main() {
        n := 10
        mm := make([]int, n+1)
        mm[0] = 1
        for i := 1; i <= n; i++ {
            for k := 1; k <= 3; k++ {
                if i-k >= 0 {
                    mm[i] += mm[i-k]
                }
            }
        }
        fmt.Println(mm)
        fmt.Println(mm[n])
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛