-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClimbing_Stairs.py
More file actions
109 lines (83 loc) · 2.44 KB
/
Climbing_Stairs.py
File metadata and controls
109 lines (83 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
'''
Variable a tells you the number of ways to reach the current step,
and b tells you the number of ways to reach the next step.
So for the situation one step further up, the old b becomes the new a,
and the new b is the old a+b,
since that new step can be reached by climbing 1 step from what b represented or 2 steps from what a represented.
'''
class Solution:
def climbStairs(self, n):
a = b = 1
for _ in range(n):
a, b = b, a + b
return a
# Top down - TLE
class Solution:
def climbStairs(self, n):
if n == 1:
return 1
if n == 2:
return 2
return self.climbStairs(n-1)+self.climbStairs(n-2)
# Bottom up, O(n) space
class Solution:
def climbStairs(self, n):
if n == 1:
return 1
res = [0 for i in range(n)]
res[0], res[1] = 1, 2
for i in range(2, n):
res[i] = res[i-1] + res[i-2]
return res[-1]
# Bottom up, constant space
class Solution:
def climbStairs(self, n):
if n == 1:
return 1
a, b = 1, 2
for i in range(2, n):
tmp = b
b = a+b
a = tmp
return b
# Top down + memorization (list)
class Solution:
def climbStairs(self, n):
if n == 1:
return 1
dic = [-1 for i in range(n)]
dic[0], dic[1] = 1, 2
return self.helper(n-1, dic)
def helper(self, n, dic):
if dic[n] < 0:
dic[n] = self.helper(n-1, dic)+self.helper(n-2, dic)
return dic[n]
# Top down + memorization (dictionary)
class Solution:
def __init__(self):
self.dic = {1:1, 2:2}
def climbStairs(self, n):
if n not in self.dic:
self.dic[n] = self.climbStairs(n-1) + self.climbStairs(n-2)
return self.dic[n]
# Using dp
class Solution:
def climbStairs(self, n):
#edge cases
if n==0: return 0
if n==1: return 1
if n==2: return 2
dp = [0]*(n+1) # considering zero steps we need n+1 places
dp[1]= 1
dp[2] = 2
for i in range(3,n+1):
dp[i] = dp[i-1] +dp[i-2]
print(dp)
return dp[n]
# dp concise code
class Solution:
def climbStairs(self, n: int) -> int:
steps = [1,1]
for i in range(2,n+1):
steps.append(steps[i-1] + steps[i-2])
return steps[n]