LeetCode 70. 爬楼梯

目录结构

1.题目

2.题解


1.题目

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

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

注意:给定 n 是一个正整数。

示例:

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


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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/climbing-stairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2.题解

 由表可知,

  • 当n=1时,结果为1;
  • 当n=2时,结果为2;
  • 当n>2时,结果为n-1的结果加上n-2的结果。
1 2 3 4 5 ...
1 1+1 1+1+1 1+1+1+1 1+1+1+1+1  
  2 2+1 2+1+1 2+1+1+1  
    1+2 1+2+1 1+2+1+1  
      1+1+2 1+1+2+1  
      2+2 1+1+1+2  
        2+2+1  
        2+1+2  
        1+2+2  
1种 2种 3种 5种 8种  
public class Solution70 {
    public int climbStairs(int n) {
        if (n == 1) {
            return 1;
        }
        if (n == 2) {
            return 2;
        }
        int a = 1, b = 2, result = 0;
        for (int i = 3; i <= n; i++) {
            result = a + b;
            a = b;
            b = result;
        }
        return result;
    }
}
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)

你可能感兴趣的:(LeetCode)