leetcode刷题(三)

问题链接:https://leetcode.com/problems/climbing-stairs/description/

问题描述:爬一个长度为N的楼梯,每次可以爬一节或者两节楼梯,求出爬楼梯的方法:

我的答案:

class Solution:

    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        count=0
        if n==1:
            return 1
        else:
            t=int(n/2)
            #每次多一个2,就减去1,做从n-i的不放回抽取
            for i in range(1,t+1):
                count+=self.get_last_value(n-i,i)
            return int(count+1)
    def get_value(self,x): 
        if x==0:
            return 1
        if x==1:  
            return x  
        else:  
            return x * self.get_value(x-1)  
    def get_last_value(self,x,m):  
        first = self.get_value(x)   
        second = self.get_value(m)   
        third = self.get_value((x-m))  

        return first/(second * third)  

这里我用的是二项式的方法,时间负责度为O(n),空间负责度为1。


看看大佬的代码:

int getClimbingways(int n){

if(n<1){

retuen 0;

}

if(n==1){

retuen 1;

}

if(n==2){

return 2;

}

int a=1;

int b=2;

int temp=0;

for(int i=3,i<=n,i++)

   temp=a+b;

   a=b;

   b=temp;

}

return temp;

}

这个算法很高级,是动态规划实现,时间负责度为O(n),空间复杂度为O(1)

详细分析参见:http://mp.weixin.qq.com/s/3h9iqU4rdH3EIy5m6AzXsg,超生动可爱的动态规划讲解,还有另一个难题,还没看懂,看懂得同学可要给我科普一下,先谢过了。

猜你喜欢

转载自blog.csdn.net/weixin_38368941/article/details/79808647