java递归常见问题实现
1 求数组最大元素
2 汉诺塔问题
3 进制转换问题
4 斐波那契数列求解
5 阶乘问题
java递归思想笔记
1 递归的基本公式和结束条件
2 递归不断的在内存中建立新的执行环境
3 要把大的问题一步一步分解,递归是一种思想。
java递归常见问题实现源代码
package com.marthevin.recursive;
public class RecursiveTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
RecursiveTest test = new RecursiveTest();
// int[] list = {98,3,2,45,6,34,24,63,43,55,53,23,34,32,53,23};
// System.out.println(test.getLargest(list, 0, list.length-1));
// test.moveDisks(4, 1, 3, 2);
test.decToBin(1892, 2);
}
public int getLargest(int[] list,int lowerIndex,int upperIndex)
{
int max = 0;
if(lowerIndex == upperIndex)
{
return list[lowerIndex];
}else{
max = getLargest(list,lowerIndex+1,upperIndex);
System.out.println("max= "+max);
if(max>=list[lowerIndex]) return max;
else return list[lowerIndex];
}
}
public double rFibNum(double a,double b,int n)
{
if(n==1) return a;
else if(n==2) return b;
else return rFibNum(a, b, n-1)+rFibNum(a, b, n-2);
}
public void moveDisks(int n,int needle1,int needle3,int needle2)
{
if(n>0)
{
moveDisks(n-1,needle1,needle2,needle3);
System.out.println("move disk "+n+" from needle "+needle1+" to needle "+needle3);
moveDisks(n-1, needle2, needle3, needle1);
}
}
public void decToBin(int num,int base)
{
if(num>0)
decToBin(num/base, base);
System.out.print(num%base);
}
}