Thinking in java-16 递归和迭代

来源:互联网 发布:电脑找不到windows 编辑:程序博客网 时间:2024/05/20 16:36

1.递归和迭代异同Recursion & Iteration

这里有关于此问题的Quora解答。
An algorithm is a procedure or formula for solving a problem.If you want to repeat some steps in procedure you can opt Iterative algorithm or Recursive algorithm, but both may successfully accomplish the same task.

An Iterative algorithm will use looping statements such as for loop, while loop or do-while loop to repeat the same steps while a Recursive algorithm, a function calls itself again and again till the base condition(stopping condition) is satisfied.

An Iterative algorithm will be faster than the Recursive algorithm because of overheads like calling functions and registering stacks repeatedly. Many times the recursive algorithms are not efficient as they take more space and time.

Recursive algorithms are mostly used to solve complicated problems when their application is easy and effective. For example Tower of Hannoi algorithm is made easy by recursion while iterations are widely used, efficient and popular.

  1. 迭代算法使用循环语句,如while/for循环来重复相同的一些步骤;而递归算法是通过重复调用其自身直到基准条件满足时返回。
  2. 迭代算法运行更快,但代码的可理解性和代码的复杂度很高。
  3. 递归算法的代码可理解性和代码复杂度低,但需要不断调用函数并使用寄存器堆栈,所以算法的开销很大,时间空间代价大。

2.实例 Fibonacci Series

class Fibonacci{    public long fibRecur(int n){        if(n<2)            return 1;        return fibRecur(n-2)+fibRecur(n-1);    }    public long fibIter(int n){        long prev, next, res;        next = res = 0;        while(n-->1){            prev = next;            next = res;            res = prev+next;        }        return res;    }}
原创粉丝点击