zoukankan      html  css  js  c++  java
  • LeetCode OJ——Climbing Stairs

    http://oj.leetcode.com/problems/climbing-stairs/

    走台阶的题目,转换出数学模型之后,就是Fibonacci数列。后一个数等于前两个数的和。

    递归版本超时,代码如下:

    class Solution {
    public:
        int walk(int sum)
        {
            if(sum == 0 )
                return 1;
            if(sum ==1)
                return 1;
            return walk(sum-1)+walk(sum-2);
        }
    
    
        int climbStairs(int n) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            return walk(n);
        }
    };

    然后改成顺序的了,AC,代码如下:

    #include <iostream>
    
    using namespace std;
    
    class Solution {
    public:
    
        int climbStairs(int n) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            int* arr = (int*)malloc(sizeof(int)*(n+2));
            arr[0] = 1;
            arr[1] = 1;
    
            for(int i = 2;i<=n;i++)
                arr[i] = arr[i-1]+arr[i-2];
            return arr[n];
        }
    };
    
    
    int main()
    {
        Solution myS;
        int ans = myS.climbStairs(25);
    
        cout<<ans<<endl;
        
        return 0;
    }

    加油!

  • 相关阅读:
    对坐标点的离散化
    线段树-离散化处理点
    树状数组
    线段树
    dfs
    vector
    go 参数传递的是值还是引用 (转)
    go 数组指针 指针数组
    go 协程
    go 接口实现
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3417151.html
Copyright © 2011-2022 走看看