递归基础训练题目:
(一)重复中找变化,变化中找重复-切蛋糕
(1)求阶乘
(2)打印i-j
(3)数组求和
(4)翻转字符串
(二)划不开-递推公式,等价转换
(5)斐波那契数列
(6)最大公约数-辗转相除法
(7)插入排序转递归
(8)汉诺塔
//########################递归问题#################
//#####(一)重复中找变化,变化中找重复#####
public class Main
{
//(1)求阶乘
static int f1(int n)
{
if(n==1) return 1;
return n* f1(n-1);
}
//(2)打印i-j
static int f2(int i,int j)
{
if(i==j+1) return 0;
else
{
System.out.print(i+" ");
return f2(i+1,j);
}
}
//(3)数组求和
static int f3(int arr[],int index)
{
if(index==-1) return 0;
return arr[index]+f3(arr,index-1);
}
//(4)翻转字符串
static String f4(String s,int j)
{
if(j==-1) return "";
return s.charAt(j)+f4(s,j-1);
}
public static void main(String[] ars)
{
//(1)求阶乘
int n=9;
System.out.println("(1)"+f1(n));
//(2)打印i-j
System.out.print("(2)");
f2(1,10);
System.out.println();
//(3)数组元素求和
int a[]={1,2,3,4,5,6,7,8,9};
f3(a,a.length-1);
System.out.println("(3)"+f3(a,a.length-1));
//(4)翻转字符串
String s="abcd";
System.out.println("(4)"+f4(s,s.length()-1));
}
}
//#####(二)划不开-递推公式,等价转换#####
public class Main
{
//(1)斐波那契数列
static int f5(int n)
{
if(n==1||n==2) return 1;
return f5(n-1)+f5(n-2);
}
//(2)辗转相除法
static int f6(int m,int n)
{
if(m%n==0) return n;
return f6(n,m%n);
}
//(3)插入排序转递归
static void f7(int a[],int k)
{
if(k==0) return ;
f7(a,k-1);
int x=k;
while(x>0&&a[x]<a[x-1])
{
int t=0;
t=a[x];
a[x]=a[x-1];
a[x-1]=t;
x--;
}
}
//(4)###汉诺塔(从A->C)###
static void f8(int N,char from,char help,char to)
{
if(N==1)
System.out.print(from+"->"+to+' ');
else
{
f8(N-1,from,to,help);
System.out.print(from+"->"+to+' ');
f8(N-1,help,from,to);
}
}
//###汉诺塔(从A->B)###
static void f8_2(int N,char from,char to,char help)
{
if(N==1)
System.out.print(from+"->"+to+' ');
else
{
f8_2(N-1,from,help,to);
System.out.print(from+"->"+to+' ');
f8_2(N-1,help,to,from);
}
}
public static void main(String[] ars)
{
//(1)斐波那契数列
System.out.println("(1)"+f5(5));
//(2)最大公约数-辗转相除法
System.out.println("(2)"+f6(169,4));
//(3)插入排序转递归
int a[]={3,2,7,1,9};
f7(a,a.length-1);
System.out.print("(3)");
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
//(4)汉诺塔问题
System.out.print("(4)");
f8(3,'A','B','C');
System.out.println();
//(4)_2:###汉诺塔(从A->B)###
System.out.print("(4)_2:");
f8_2(3,'A','B','C');
}
}