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;
    }

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

  • 相关阅读:
    页面渲染1——创建对象模型
    HTTP 缓存
    web安全字体
    图片优化
    基于文本内容的压缩
    Mac homebrew的熟悉和常用指令
    二、Java注释
    一、Java环境变量配置
    JS中的逻辑运算符&&、||
    js 中的 深拷贝与浅拷贝
  • 原文地址:https://www.cnblogs.com/thewaytomakemiracle/p/5019425.html
Copyright © 2011-2022 走看看