java递归的应用示例

递归就是直接或间接的调用自己,体现了以此类推,重复同样的步骤。

1.三角数 所谓三角数第一项的值为1,第n项的值为n-1项的值加n,如下为java实现三角数,求第n项的值

package com.mathmatic;
/**
 * 
 * @author cdh
 *
 */
public class DiGui {
   
	public static int threeMath(int n) {
		if(n==1) {
			return 1;
		}
		return threeMath(n-1) + n;
	}
	
	
	public static void main(String[] args) {
		 System.out.println(DiGui.threeMath(4));
		//System.out.println(feiBoNaQi(5));
		//hanNuoTa(5, 'A', 'B', 'C');
	}
}

 

2.斐波那契数列 所谓斐波那契数列解释第一项的值为0,第二项的值为1,第n项的值为第n-1项的值加n-2项的值

如下为java实现斐波那契数列,求数列的第n项的值

package com.mathmatic;
/**
 * 
 * @author cdh
 *
 */
public class DiGui {
   
	
	public static int feiBoNaQi(int n) {
		if(n == 1) {
			return 0;
		}else if(n == 2) {
			return 1;
		}else {
			return feiBoNaQi(n-1) + feiBoNaQi(n-2);
		}
	}
	
	public static void main(String[] args) {
		 //System.out.println(DiGui.threeMath(4));
		System.out.println(feiBoNaQi(5));
		//hanNuoTa(5, 'A', 'B', 'C');
	}
}

3.汉诺塔问题 所谓汉诺塔就是一共有A B C 三座塔,其中A塔上堆了若干盘子,现在需要借助B塔为中间塔,将A塔上的盘子全部移动

到C塔,其中每次只能移动一个盘子,并且任何一个盘子不能放在比自己小的盘子上面

package com.mathmatic;
/**
 * 
 * @author cdh
 *
 */
public class DiGui {
   
	
	public static void hanNuoTa(int totalPan,char from,char center,char to) {
		if(totalPan == 1) {
			System.out.println("����" + totalPan + "��" + "��" + from  + "�ƶ���" +  "��" + to);
		}else {
			hanNuoTa(totalPan-1,from,to,center);
			System.out.println("����" + totalPan + "��" + "��" + from  + "�ƶ���" + "��" + to);
            hanNuoTa(totalPan-1, center, from, to);
		}
	}
	public static void main(String[] args) {
		 //System.out.println(DiGui.threeMath(4));
		//System.out.println(feiBoNaQi(5));
		hanNuoTa(5, 'A', 'B', 'C');
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值