递归(recursion)和迭代(iterate)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38497634/article/details/88914351

1.递归和迭代都是循环的一种。

2.递归是把数据处理的过程交给机器,迭代是人为推出数据处理过程后进行运算。

3.递归在使用过程中因为不断调用自身(函数调用过程中参数必须压入堆栈保存,直到该层函数返回为止),可能会导致堆栈溢出的错误。

java代码演示:

//迭代和递归解决波菲纳契数列
public class DiguiDiedai {
    static int  diedai(int n,int a,int b){
        if(n ==1){
            return n;
        }else if(n == 2){
            return n;
        }else{
            for(int i=2;i<n;i++){
                int temp;
                temp = a + b;
                a = b;
                b = temp;
            }
            return b;
        }
    }
    static int digui(int n,int a,int b){
        if(n == 1){
            return a;
        }else if(n == 2){
            return b;
        }else{
            return digui(n-1,a,b)+digui(n-2,a,b);
        }
    }
    public static void main(String[] args){
        int a,b,n;
        a = 1;
        b = 1;
        n = 5;
        System.out.println(digui(n,a,b));
        System.out.println(digui(n,a,b));
    }
}
 

猜你喜欢

转载自blog.csdn.net/qq_38497634/article/details/88914351