-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclimbing-stairs.cpp
46 lines (40 loc) · 1.16 KB
/
climbing-stairs.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
* Copyright (c) 2021, Christopher Friedt
*
* SPDX-License-Identifier: MIT
*/
// clang-format off
// name: climbing-stairs
// url: https://leetcode.com/problems/climbing-stairs
// difficulty: 1
// clang-format on
#include <vector>
using namespace std;
class Solution {
public:
int climbStairs(int n) {
// observations
// * at any step i, the previous step is either going to have been (i - 1)
// or (i - 2)
// * simple table shows the recurrance relationship NW(i) = NW(i - 1) + NW(i
// - 2)
// * technically there are overlapping subproblems, which makes this 1d dp,
// so it could be solved using a 1-d vector, but it's fairly obvious that
// there only needs to be a memory of size 2, which produces a solution
// * O(N) time and O(1) space
//
// i NW(i) NW(i-1) NW(i-2)
// ---------------------------
// 1 1 1 0
// 2 2 1 1
// 3 3 2 1
// 4 5 3 2
int prev_prev = 0;
int prev = 1;
int result = 0;
for (int i = 1; i <= n; prev_prev = prev, prev = result, ++i) {
result = prev + prev_prev;
}
return result;
}
};