leetcode(70). Climbing Stairs

来源:互联网 发布:海思摄像头软件 编辑:程序博客网 时间:2024/05/21 09:31

problem

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?

Note: Given n will be a positive integer.

solution

这是一个经典的问题,可以使用递归的方法来解决,但是这样的时间复杂度为O(2n)

class Solution(object):    def climbStairs(self, n):        """        :type n: int        :rtype: int        """        if n == 1:            return 1        elif n == 2:            return 2        else:            return self.climbStairs(n-1)+self.climbStairs(n-2)

可以发现在递归过程中重复利用之前的结果,因此我们可以使用动态规划,将问题按规模从小到大计算,将之前的结果存储起来重复利用,时间复杂度为O(n)

class Solution(object):    def climbStairs(self, n):        """        :type n: int        :rtype: int        """        tmp = [1, 1]        if n == 1:            pass        else:                for i in range(2, n+1):                tmp.append(tmp[i-1]+tmp[i-2])        return tmp[n]
原创粉丝点击