zoukankan      html  css  js  c++  java
  • 递归转非递归

    转自:http://www.cnblogs.com/kwklover/archive/2006/04/08/369923.html

    问:为什么要递归转非递归?
    答:因为每一次的递归调用都需要压栈占用内存,效率不高。

    一般的递归方法以求阶乘为例

    unsigned long long Recursive(unsigned long long n)
    {
        if (n > 1)
        {
            return n * Recursive(n - 1);
        }
        else if (n == 1)
        {
            return 1;
        }
    }
    View Code

    递归转非递归的两种方法:

    循环非递归法:

    unsigned long long NoRecursiveByLoop(unsigned long long n)
    {
        int k = 1;
        int t = 1;
        while (k <= n)
        {
            t *= k;
            k++;
        }
        
        return t;
    }
    View Code

    自定义堆栈非递归法:

    unsigned long long NoRecursiveByStack(unsigned long long n)
    {
        Stack<int> s = new Stack<int>();
        int t = 1;
        int temp;
        s.Push(n);
        while ((temp = s.Peek()) != 1)
        {
            t *= s.Peek();
            s.Pop();
            s.Push(temp - 1);
        }
        return t;
    }
    View Code
  • 相关阅读:
    codeforces 980A Links and Pearls
    zoj 3640 Help Me Escape
    sgu 495 Kids and Prizes
    poj 3071 Football
    hdu 3853 LOOPS
    hdu 4035 Maze
    hdu 4405 Aeroplane chess
    poj 2096 Collecting Bugs
    scu 4444 Travel
    zoj 3870 Team Formation
  • 原文地址:https://www.cnblogs.com/MarkGrid/p/3135419.html
Copyright © 2011-2022 走看看