zoukankan      html  css  js  c++  java
  • 爬楼梯问题——迭代or递归

    采用递归法爬楼梯效率真是惊人啊,所以呢。用迭代吧。

    下面是递归的。

    #include <iostream>
    #include <vector>
    #include <math.h>
    #include <time.h>
    
    using namespace std;
    
    class Solution {
    public:
        int climbStairs(int n)
        {
            int step = 0;
            if(n == 1)
            {
                return 1;
            }
            else if (n == 2)
            {
                return 2;
            }
            else
            {
                step = climbStairs(n - 1) + climbStairs(n - 2);
            }
            return step;
        }
    };
    int main(int argc, const char * argv[])
    {
        Solution A;
        clock_t start,end;
        double time;
        start = clock();
        int num;
        while (cin>>num)
        {
            cout<<A.climbStairs(num)<<endl;
            break;
        }
        end = clock();
        time = (double)(end - start) / CLOCKS_PER_SEC;
        cout<<time<<endl;
    
        // insert code here...
        
        return 0;
    }                                                                                                       

    下面是迭代的。

    #include <iostream>
    #include <vector>
    #include <math.h>
    #include <time.h>
    
    using namespace std;
    
    
    
    class Solution {
    public:
        int climbStairs(int n)
        {
            int step = 0;
            int k;
            if (n == 1)
            {
                step = 1;
            }
            else if (n == 2)
            {
                step = 2;
            }
            else
            {
                k = 2;
                ans[0] = 1;
                ans[1] = 2;
                while (k != n)
                {
                    ans[k] = ans[k - 1] + ans[k - 2];
                    k++;
                }
                step = ans[k - 1];
            }
            return step;
        }
    private:
        int ans[100];
    };
    int main(int argc, const char * argv[])
    {
        Solution A;
        clock_t start,end;
        double time;
        start = clock();
        int num;
        while (cin>>num)
        {
            cout<<A.climbStairs(num)<<endl;
        }
        end = clock();
        time = (double)(end - start) / CLOCKS_PER_SEC;
        cout<<time<<endl;
    
        // insert code here...
        
        return 0;
    }

    自己测试一下,如果数据量稍大,两种方法将会爆炸。。

  • 相关阅读:
    PGA
    impdp导入job
    11g SQL Monitor
    Oracle buffer cache
    OGG异常处理
    Android中dp、dpi与px的关系
    android:gravity设置居中的问题
    Oracle触发器详解
    Android selector中的item的顺序
    selector在color和drawable目录下的区别
  • 原文地址:https://www.cnblogs.com/thewaytomakemiracle/p/5019425.html
Copyright © 2011-2022 走看看