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

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

  • 相关阅读:
    HDU 3729【二分匹配】
    51nod 1456【强连通,缩点,并查集】
    51nod1459【二级最短路】
    51nod1640 【最小生成树】
    CodeForces660B【模拟—水】
    CodeForces691C 【模拟】
    Codeforces698B【并查集+拆环】
    CodeForces717C 【数学】
    Codeforces710C【数学】
    HDU5904【瞎搞】
  • 原文地址:https://www.cnblogs.com/thewaytomakemiracle/p/5019425.html
Copyright © 2011-2022 走看看