-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClimbing_Stairs.py
61 lines (56 loc) · 1.52 KB
/
Climbing_Stairs.py
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
# 第一种思路,使用组合计算公式
# 36ms 78.71%
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
def c(n, m):
def factorial(num):
if num is 0:
return 1
else:
return num * factorial(num - 1)
return factorial(n) / (factorial(m) * factorial(n - m))
res = 1
index = 1
while index * 2 <= n:
res += c(n - index * 2 + index, index)
index += 1
return int(res)
# 第二种思路,使用动态规划,但是超时了
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n is 1:
return 1
elif n is 2:
return 2
else:
return self.climbStairs(n - 1) + self.climbStairs(n - 2)
# 第三种思路,使用基于备忘录的动态规划
# 32ms 99.97%
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
memo = {}
def dp(n):
if n in memo:
return memo[n]
else:
if n is 1:
ans = 1
elif n is 2:
ans = 2
else:
ans = dp(n - 1) + dp(n - 2)
memo[n] = ans
return memo[n]
return dp(n)