首页 > 编程语言 > 详细

研磨数据结构与算法-06递归的应用

时间:2015-09-21 01:52:03      阅读:268      评论:0      收藏:0      [点我收藏+]

一,简单Demo

public class Recursion {

public static void main(String[] args) {

test(100);

}

public static void test(int n) {

if(n == 0) {

return;

}

System.out.println(n); 

test2(n - 1);

}

}

二,三角数字


public class Triangle {

public static int getNumber(int n) {

int total= 0;

while(n > 0) {

total = total + n;

n--;

}

return total;

}

public static int getNumberByRecursion(int n) {

if(n == 1) {

return 1;

} else {

return n + getNumberByRecursion(n - 1);

}

}

}

测试:

public class TestTriangle {

public static void main(String[] args) {

System.out.println(Triangle.getNumber(500));

System.out.println(Triangle.getNumberByRecursion(500));

}

}

三,斐波那契数列

public class Fibonacci {

public static int getNumber(int n) {

if(n == 1) {

return 0;

} else if(n == 2){

return 1;

} else {

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

}

}

}

测试:

public class TestFibonacci {

public static void main(String[] args) {

System.out.println(Fibonacci.getNumber(5));

}

}


本文出自 “8159085” 博客,请务必保留此出处http://8169085.blog.51cto.com/8159085/1696501

研磨数据结构与算法-06递归的应用

原文:http://8169085.blog.51cto.com/8159085/1696501

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!