forked from y-ncao/Python-Study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClimbing_Stairs.py
46 lines (39 loc) · 1.12 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
"""
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
"""
class Solution:
# @param n, an integer
# @return an integer
def climbStairs(self, n):
return self.climbStairs_2(n)
def climbStairs_1(self, n):
if n <= 2:
return n
return self.climbStairs(n-1) + self.climbStairs(n-2)
def climbStairs_2(self, n):
if n <= 1:
return n
dp = [ 0 for i in range(n)]
dp[0] = 1
dp[1] = 2
for i in range(2, n):
dp[i] = dp[i-1] + dp[i-2]
return dp[n-1]
# Note:
# 1. dp[i] means from 0 to i-1 stair, how many ways to go
# 2. dp[0] = 1, dp[1] = 2
# 3. dp[i] = d[i-1] + dp[i-2]
# 4. dp[N-1]
def climbStairs_3(self, n):
if n <= 2:
return n
fn_1 = 1
fn_2 = 2
for i in range(3, n+1):
fn = fn_1 + fn_2
fn_1 = fn
fn_2 = fn_1
return fn
# Note:
# DP way is the best, and no need to check if n <= 2 or not.