写了个top-down的divide and conquer程序,可惜超时了。
class Solution:
def climbStairs(self, n: int) -> int:
# divide and conquer?
if n == 0:
return 1
if n <= 1:
return self.climbStairs(n-1)
if n >= 2:
return self.climbStairs(n-1) + self.climbStairs(n-2)
写个bottom up的DP程序,还是比较清楚的。
induction的初始值,以及推导步骤。
就是到每个节点的可能有两种:1种是经过它前面的一个节点,再一跳。另一种是不经过它前面的节点,从它前两个那里,跳两个台阶。
所以ways[n] = ways[n-1]+ways[n-2]
class Solution:
def climbStairs(self, n: int) -> int:
# treat it as a DP problem
# number of possible ways to the ith step
ways = [0 for i in range(n)]
if n==1: return 1
if n==2: return 2
ways[0] = 1 # only one choice for 1 step
ways[1] = 2 # only two choices for two steps
for i in range(2,n):
ways[i] = ways[i-1] + ways[i-2]
# only 2 choices, passing i-1th node or not passing it
# passing the i-1th node by doing one step
# not passing the i-1th node by doing two steps
# so when combined, it will all the possibilities.
return ways[n-1]
因为其实用不到存储那么多值,只需要两个变量就可以了。
主要是需要搞好ways_prev2, 和ways_prev初始值的顺序,不然就错了。
这就是个斐波那契数列。
class Solution:
def climbStairs(self, n: int) -> int:
# treat it as a DP problem
# number of possible ways to the ith step
if n==1: return 1
if n==2: return 2
ways_prev2 = 1 # only one choice for 1 step
ways_prev = 2 # only two choices for two steps
for i in range(2,n):
ways = ways_prev + ways_prev2
# only 2 choices, passing i-1th node or not passing it
# passing the i-1th node by doing one step
# not passing the i-1th node by doing two steps
# so when combined, it will all the possibilities.
ways_prev2 = ways_prev
ways_prev = ways
return ways