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