Featured image of post 70. 爬楼梯

70. 爬楼梯

题目描述

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。

每次你可以爬 12 个台阶。你有多少种不同的方法可以爬到楼顶呢?

示例 1:

  • 输入:n = 2
  • 输出:2
  • 解释:有两种方法可以爬到楼顶。
    • 1 阶 + 1 阶
    • 2 阶

示例 2:

  • 输入:n = 3
  • 输出:3
  • 解释:有三种方法可以爬到楼顶。
    • 1 阶 + 1 阶 + 1 阶
    • 1 阶 + 2 阶
    • 2 阶 + 1 阶

提示:

  • 1 <= n <= 45

解法一:动态规划

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
func climbStairs(n int) int {
    if n <= 2 {
        return n
    }
    a, b := 1, 2
    for i := 3; i <= n; i++ {
        tmp := b
        b = a + b
        a = tmp
    }
    return b
}

解法二:通项公式

1
2
3
4
5
6
func climbStairs(n int) int {
    sqrt5 := math.Sqrt(5)
    pow1 := math.Pow((1+sqrt5)/2, float64(n+1))
    pow2 := math.Pow((1-sqrt5)/2, float64(n+1))
    return int(math.Round((pow1 - pow2) / sqrt5))
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2023/05/19 11:26:17
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计