码迷,mamicode.com
首页 > 其他好文 > 详细

递归调用

时间:2015-08-12 01:14:45      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:

递归:在一个方法的内部,对自身进行调用,又叫递归调用

循环和递归都要具有三部分:初始值,终止条件,前进步长

递归和迭代是等价的

常见的问题:累加加和(累乘乘积),汉诺塔,斐波那契数列

public class Recuresion_06 {

public static void main(String[] args) {

// TODO Auto-generated method stub

System.out.println(factorial(10));

System.out.println("!!!!!!!!!!!!!!!!!!!");

System.out.println(fibonacci(10));

System.out.println("!!!!!!!!!!!!!!!!!!!");

System.out.println(fibIteration(5));

}

// 阶乘:factorial

public static int factorial(int n) {

if (n == 1) {

return 1;

} else {

System.out.print(n + "*" + (n - 1) + ",");

return n * factorial(n - 1);

}

}

// 斐波那契数列

public static int fibonacci(int n) {

if (n == 1 || n == 2) {

return 1;

} else {

System.out.print((n - 1) + "+" + (n - 2) + ",");

return fibonacci(n - 1) + fibonacci(n - 2);

}

}

// 斐波那契数列,迭代实现;iteration

public static long fibIteration(int index) {

if (index == 1 || index == 2) {

return 1;

}

long f1 = 1l;

long f2 = 1l;

long f = 0;

for (int i = 0; i < index-2; i++) {

f = f1 + f2;

f1 = f2;

f2 = f;

System.out.print(f2 + "+" + f1 + ",");

}

return f;

}

}

递归调用

标签:

原文地址:http://www.cnblogs.com/lianggx66/p/4722631.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!