Leetcode 70. Climbing Stairs

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Climbing Stairs

2. Solution

  • f(n) = f(n - 1) + f(n - 2)

  • O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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;
}
};

Reference

  1. https://leetcode.com/problems/climbing-stairs/description/
如果有收获,可以请我喝杯咖啡!