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条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?