File tree Expand file tree Collapse file tree 2 files changed +70
-1
lines changed
Expand file tree Collapse file tree 2 files changed +70
-1
lines changed Original file line number Diff line number Diff line change 1+ '''Leetcode- https://leetcode.com/problems/climbing-stairs/ '''
2+ '''
3+ You are climbing a staircase. It takes n steps to reach the top.
4+
5+ Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
6+
7+
8+
9+ Example 1:
10+
11+ Input: n = 2
12+ Output: 2
13+ Explanation: There are two ways to climb to the top.
14+ 1. 1 step + 1 step
15+ 2. 2 steps
16+ '''
17+ #Top down TLE #T:O(2^n)
18+ def climbStairs (n ):
19+ if n == 1 :
20+ return 1
21+ if n == 2 :
22+ return 2
23+
24+ return climbStairs (n - 1 )+ climbStairs (n - 1 )
25+
26+ #Top down + memorization (list)
27+ def climbStairs (self ,n ):
28+ if n == 1 :
29+ return 1
30+ arr = [- 1 for i in range (n )]
31+ arr [0 ], arr [1 ] = 1 , 2
32+ return self .helper (n - 1 , arr )
33+
34+ def helper (self , n , arr ):
35+ if arr [n ] < 0 :
36+ arr [n ] = self .helper (n - 1 , arr )+ self .helper (n - 2 , arr )
37+ return arr [n ]
38+
39+ # Top down + memorization (dictionary/hashmap) #TLE
40+ def climbStairs (n ):
41+ dic = {1 :1 ,2 :2 }
42+ if n not in dic :
43+ dic [n ] = climbStairs (n - 1 )+ climbStairs (n - 2 )
44+ return dic [n ]
45+
46+ # Bottom up, O(n) space
47+ def climbStairs (n ):
48+ if n == 1 :
49+ return 1
50+ res = [0 for i in range (n )]
51+ res [0 ],res [1 ] = 1 ,2
52+
53+ for i in range (2 ,n ):
54+ res [i ] = res [i - 1 ] + res [i - 2 ]
55+ return res [- 1 ]
56+
57+ # Bottom up, constant space
58+ def climbStairs (n ):
59+ one ,two = 1 ,1
60+
61+ for i in range (n - 1 ):
62+ temp = one
63+ one = one + two
64+ two = temp
65+ return one
66+
67+ #T:O(n)
Original file line number Diff line number Diff line change @@ -16,4 +16,6 @@ Check the notes for the explaination - [Notes](https://stingy-shallot-4ea.notion
1616- [x] [ Matrix] ( Matrix )
1717 - [x] [ Word Search] ( Matrix/79-Word-Search.py )
1818- [x] [ Dynamic Programming] ( Dynamic-Programming )
19- - [x] [ Combination Sum] ( Dynamic-Programming/39-Combination-Sum.py )
19+ - [x] [ Combination Sum] ( Dynamic-Programming/39-Combination-Sum.py )
20+ - [x] [ Climbing Stairs] ( Dynamic-Programming/70-Climbing-Stairs.py )
21+
You can’t perform that action at this time.
0 commit comments