Leetcode 70. Climbing Stairs

2019-05-25 22:58:13 浏览数 (1)

1. Description

2. Solution

  • f(n) = f(n - 1) f(n - 2)
  • O(n)
代码语言:javascript复制
class Solution {
public:
    int climbStairs(int n) {
        if(n == 1) {
            return 1;
        }
        int mem[n] = {0};
        mem[0] = 1;
        mem[1] = 2;
        for(int i = 2; i < n; i  ) {
            mem[i] = mem[i - 1]   mem[i - 2];
        }
        return mem[n - 1];
    }
};
  • O(n)
代码语言:javascript复制
class Solution {
public:
    int climbStairs(int n) {
        if(n == 1) {
            return 1;
        }
        int first = 1;
        int second = 2;
        int third = 0;
        for(int i = 2; i < n; i  ) {
            third = first   second;
            first = second;
            second = third;
        }
        return second;
    }
};

0 人点赞