Thinking in java-16 递归和迭代

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值