在本文开始之前,先实现两个简单的例子:
第一个,实现n!的阶乘:
实现代码:
package com.panther.demo.exercise11;
/**
* 递归,伪递归,迭代实现n!
* Created by panther.dongdong on 2016/3/18.
*/
public class RecursionTest {
public static void main(String[] args) {
System.out.println(recurse(5)); //递归显示
System.out.println(camouflageRecurse(5, 1)); //伪递归
System.out.println(iteration(5)); //迭代
}
/**
* n的阶乘,伪递归实现方式
*
* @param n
* @param result 计算保存的中间结果
* @return 最终结果
*/
public static int camouflageRecurse(int n, int result) {
if (n == 1) {
return result;
} else {
result = result * n;
return camouflageRecurse(n - 1, result);
}
}
/**
* 求 n 的阶乘递归调用方式
*
* @param n n个数的阶乘
* @return n个数阶乘的结果
*/
public static int recurse(int n) {
if (n == 1) {
return 1;
} else {
return n * recurse(n - 1);
}
}
/**
* 用迭代的方法实现n的阶乘
*
* @param n
* @return
*/
public static int iteration(int n) {
int result = 1;
for (int i = 2; i <= n; ++i) {
result *= i;
}
return result;
}
}
第二个:输出斐波那契数列:
实现代码:
package com.panther.demo.exercise11;
/**
* 斐波那契数列的递归和迭代实现求和
* 0 1 1 2 3 5 8 13 21 34 55 89
* Created by panther.dongdong on 2016/3/18.
*/
public class FibonacciTest {
public static void main(String[] args) {
System.out.println(fibonacciRecurse(14));
System.out.println(fibonacciIteration(14));
System.out.println(camouflageFibonacci(14,0));
}
/**
* 递归调用实现斐波那契数列
*
* @param n
* @return
*/
public static int fibonacciRecurse(int n) {
if (n == 1) {
return 0;
} else if (n == 2) {
return 1;
} else {
return fibonacciRecurse(n - 1) + fibonacciRecurse(n - 2);
}
}
/**
* 迭代实现斐波那契数列
* 0 1 1 2 3 5 8 13 21 34 55 89
*
* @param n
* @return
*/
public static int fibonacciIteration(int n) {
int fab = 0; //最终结果 n的值
int pre = 1; //记录n-1值
int p = 0; //记录n-2的位置
if (n == 1) {
fab = 0;
} else if (n == 2) {
fab = 1;
}
for (int i = 2; i < n; ++i) {
fab = pre + p;
p = pre;
pre = fab;
}
return fab;
}
/**
* 斐波那契数列伪递归实现
* 0 1 1 2 3 5 8 13 21 34 55 89
*
* @param n
* @return
*/
public static int camouflageFibonacci(int n, int result) {
if (n == 1) {
return 0;
} else if (n == 2) {
return 1;
} else {
result = camouflageFibonacci(n - 1, result) + camouflageFibonacci(n - 2, result);
return camouflageFibonacci(n - 1, result) + camouflageFibonacci(n - 2, result);
}
}
}