• leetcode 70 爬楼梯


    用阶乘公式算数字越界了,的确进行了一些不必要的计算,代码贴着留个纪念,局限:能进行小数字的计算

    C++:

     1 class Solution {
     2 public:
     3     int climbStairs(int n) {
     4         int res=1,i=1;
     5         while(n>1){
     6             n=n-2;
     7             int m=n+i;
     8             int temp=tm(m)/(tm(i)*tm(m-i));
     9             res+=temp;
    10             i++;
    11         }
    12         return res;
    13     }
    14     int tm(int n){
    15         if(n==0) return 1;
    16         return n*tm(n-1);
    17     }
    18 };

     卧槽我怎么没想到爬楼梯问题就是斐波那契数列,那就用递归,为了降低复杂度也就是使用记忆化搜索,也就是动态规划的方法,写出状态转移方程,降低空间复杂度

    python方法:直接从头计算斐波那契数列

    class Solution(object):
        def climbStairs(self, n):
            """
            :type n: int
            :rtype: int
            """
            #空间复杂度2,时间复杂度n
            a=0
            b=1
            for i in range(n):
                a,b=b,a+b
            return b

     python:O(n) 时间,O(1)空间

    class Solution(object):
        def climbStairs(self, n):
            """
            :type n: int
            :rtype: int
            """
            x,y=0,1
            #range(n)为左闭右开区间[0,n)
            for _ in range(n):
                x,y=y,x+y
                #print("x
    ")
            return y
  • 相关阅读:
    LeetCode 8 有效的括号
    String源码学习
    LeetCode 7最长公共前缀
    LeetCode 5回文数
    LeetCode 6罗马数字转整数
    LeetCode 4.反转整数
    LeetCode 3.无重复字符的最长子串
    区分子串和子序列
    LeetCode 1.两数之和
    一个十分好用的动画工具:Velocity.js
  • 原文地址:https://www.cnblogs.com/joelwang/p/10480827.html
Copyright © 2020-2023  润新知