【LeetCode-Algorithms】70. Climbing Stairs

题目

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.

题目大意

你正在爬楼梯的情况。这需要n步骤,以达到顶端。
每次你可以爬1或2步。你可以爬多少个不同的方式爬上去?
注意:给定n将为正整数。

解题思路

这里用逆向思维比较好理解,要使用1或2的步长走到第N个台阶,有如下两种可能性:
1、从第N-1个台阶向上走1
2、从第N-2个台阶向上走2
当台阶数大于等于2时均成立,所以得到如下表达式:
1、当n=1时,总可能性为1
2、当n=2时,总可能性为2
3、当n=m时,总可能性=m-1的可能性+m-2的可能性

class Solution {
public:
    int climbStairs(int n) {
        if (n <= 1)
        {
            return 1;
        }
        
        int last1 = 2, last2=1, next=0;
        for (int num = 2; num < n; ++num)
        {
            next = last1 + last2;
            last2 = last1;
            last1 = next;
        }
        return last1;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容