美文网首页
4.LeetCode刷题For Swift·70. Climbi

4.LeetCode刷题For Swift·70. Climbi

作者: 富城 | 来源:发表于2020-12-26 09:24 被阅读0次

1、原题

You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Example 1:

Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

2、思路

3、代码

class Solution {
    func climbStairs(_ n: Int) -> Int {
        // 这个问题归纳之后为f(n) = f(n-1)+f(n-2),典型的斐波那契数列问题
        //前两个比较特殊,直接输出
        if n <= 2 {
            return n
        }
        var a = 1
        var b = 2
        // 定义两个变量作为循环传值 
        // 经过一次次的传递  就算出最后的结果
        for i in 3...n {
            let tmp = b
            b = a + b
            a = tmp
        }
        return b
    }
}

相关文章

网友评论

      本文标题:4.LeetCode刷题For Swift·70. Climbi

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