Skip to content

Commit a13fcc3

Browse files
committed
Implement climbing-stairs
name: climbing-stairs url: https://leetcode.com/problems/climbing-stairs difficulty: 1 time: 100.0 ms time-rank: -1 % time-complexity: O(N) space: 5.8 MB space-rank: 100.0 % space-complexity: O(1) Fixes #298 Signed-off-by: Christopher Friedt <[email protected]>
1 parent b5d8d5f commit a13fcc3

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

climbing-stairs-test.cpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
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)); }

climbing-stairs.cpp

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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+
};

0 commit comments

Comments
 (0)