Skip to content

Commit 049e4db

Browse files
Add files via upload
1 parent bbfc9c8 commit 049e4db

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Climbing Stairs/Climbing_Stairs.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# 第一种思路,使用组合计算公式
2+
# 36ms 78.71%
3+
class Solution:
4+
def climbStairs(self, n):
5+
"""
6+
:type n: int
7+
:rtype: int
8+
"""
9+
def c(n, m):
10+
def factorial(num):
11+
if num is 0:
12+
return 1
13+
else:
14+
return num * factorial(num - 1)
15+
return factorial(n) / (factorial(m) * factorial(n - m))
16+
17+
res = 1
18+
index = 1
19+
20+
while index * 2 <= n:
21+
res += c(n - index * 2 + index, index)
22+
index += 1
23+
24+
return int(res)
25+
26+
# 第二种思路,使用动态规划,但是超时了
27+
class Solution:
28+
def climbStairs(self, n):
29+
"""
30+
:type n: int
31+
:rtype: int
32+
"""
33+
if n is 1:
34+
return 1
35+
elif n is 2:
36+
return 2
37+
else:
38+
return self.climbStairs(n - 1) + self.climbStairs(n - 2)
39+
40+
# 第三种思路,使用基于备忘录的动态规划
41+
# 32ms 99.97%
42+
class Solution:
43+
def climbStairs(self, n):
44+
"""
45+
:type n: int
46+
:rtype: int
47+
"""
48+
memo = {}
49+
def dp(n):
50+
if n in memo:
51+
return memo[n]
52+
else:
53+
if n is 1:
54+
ans = 1
55+
elif n is 2:
56+
ans = 2
57+
else:
58+
ans = dp(n - 1) + dp(n - 2)
59+
memo[n] = ans
60+
return memo[n]
61+
return dp(n)

0 commit comments

Comments
 (0)