Leetcode 70. Climbing Stairs

1. Description

2. Solution

  • f(n) = f(n - 1) + f(n - 2)
  • O(n)
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)
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 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券