Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1242 from aniruddhakj/patch-1
Browse files Browse the repository at this point in the history
Updating 70.climbing_stairs.cpp
  • Loading branch information
Ahmad-A0 authored Oct 9, 2022
2 parents 3d16d54 + cabffc3 commit 71d4c5c
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions cpp/neetcode_150/13_1-d_dynamic_programming/climbing_stairs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,31 @@
Climbing stairs, either 1 or 2 steps, distinct ways to reach top
Ex. n = 2 -> 2 (1 + 1, 2), n = 3 -> 3 (1 + 1 + 1, 1 + 2, 2 + 1)
Recursion w/ memoization -> DP, why DP? Optimal substructure
Bottom-up DP
Recurrence relation: dp[i] = dp[i - 1] + dp[i - 2]
Reach ith step in 2 ways: 1) 1 step from i-1, 2) 2 steps from i-2
Time: O(n)
Space: O(1)
*/

class Solution {
class SolutionBottomUp {
public:
//Fibonacci series : 'one' stores ways from [n-2]
//'two' stores ways from [n-1]
int climbStairs(int n) {
int one = 1, two = 1;
for(int i = 0; i < n - 1; ++i){
int temp = one;
one += two;
two = temp;
}
return one;
}
};


class SolutionTopDown {
public:
int climbStairs(int n) {
if (n == 1) {
Expand Down

0 comments on commit 71d4c5c

Please sign in to comment.