美文网首页LeetCode By Go
[LeetCode By Go 72]70. Climbing

[LeetCode By Go 72]70. Climbing

作者: miltonsun | 来源:发表于2017-08-30 14:39 被阅读3次

题目

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

解题思路

1个台阶有1种方案
2个台阶有2种方案
3个台阶有3=2+1种方案
...
n个台阶有f(n) = f(n-1) + f(n-2)种方案

使用递归的话会超时,所以使用循环计算

代码

func climbStairs(n int) int {
    if 1 == n {
        return 1
    } else if 2 == n {
        return 2
    }
    

    ret1 := 1
    ret2 := 2
    var ret int
    for i := 2; i < n; i++ {
        ret = ret1 + ret2
        ret1 = ret2
        ret2 = ret
    }
    
    return ret
}

相关文章

网友评论

    本文标题:[LeetCode By Go 72]70. Climbing

    本文链接:https://www.haomeiwen.com/subject/slptjxtx.html