Climbing stairs (70)

写了个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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值