Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f1ec9e4

Browse files
Climbing Stairs
1 parent cef087b commit f1ec9e4

File tree

2 files changed

+69
-1
lines changed

2 files changed

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

‎README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,5 @@ Check the notes for the explaination - [Notes](https://stingy-shallot-4ea.notion
2222
- [x] [Generalized Abbreviation](Backtracking/320-Generalized-Abbreviation.py)
2323
- [x] [N-Queens](Backtracking/51-N-Queens.py)
2424

25-
25+
- [x] [Dynamic Programming](Dynamic-Programming)
26+
- [x] [Climbing Stairs](Dynamic-Programming/70-Climbing-Stairs.py)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /