递归是什么:
就是这个函数内部调用了自己
打印从i到j的数
package 递归;
import java.util.Scanner;
public class 打印 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i=sc.nextInt();
int j=sc.nextInt();
f(i,j);
}
private static void f(int i,int j) {
if(i>j) return;
System.out.print(i+" ");
f(i+1,j);
}
}
计算阶乘
package 递归;
import java.util.Scanner;
public class 阶乘 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(f(n));
}
private static int f(int n) {
// TODO Auto-generated method stub
if(n==1) {
return 1;
}
return n*f(n-1);
}
}
数组求和
package 递归;
import java.util.Scanner;
public class 数组求和 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr1 = new int[n];
for(int i=0;i<n;i++) {
arr1[i] = sc.nextInt();
}
System.out.print(f(arr1,0)+"");
}
private static int f(int[] arr,int begin) {
if(begin==arr.length-1) return arr[begin];
return arr[begin]+f(arr,begin+1);
}
}
字符串翻转
package 递归;
import java.util.Scanner;
public class 字符串翻转 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String n = sc.nextLine();
System.out.print(f(n,n.length()-1));
}
private static String f(String sec,int end) {
if(end==0) {
return ""+sec.charAt(0);
}
return sec.charAt(end)+f(sec,end-1);
}
}
最大公约数
package 递归;
import java.util.Scanner;
public class 最大公约数 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
System.out.println(f(m,n));
}
private static int f(int m,int n) {
if(m%n==0) {
return n;
}
return f(m,m%n);
}
}
汉诺塔游戏
package 递归;
import java.util.Scanner;
public class 汉诺塔游戏 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
f(n,"A","B","C");
}
private static void f(int n,String from,String to,String help) {
if(n==1) {
System.out.println("move "+n+" from "+from+" to "+to);
return;
}
f(n-1,from,to,help);//先把前n-1个盘子放到辅助空间上去
System.out.println("move "+n+" from "+from+" to "+to);//把n放到要放置的空间上
f(n-1,help,to,from);//让n-1个盘子放置到源空间上去
}
}
思考过程及答题模板
1.找重复
a.找到一种划分方法(切蛋糕,多分支)
b.找到递推公式或者等价转换
都是父问题转化为求解子问题
2.找变化的量
变化的量通常要作为参数
3.找出出口
public static void main(String[] args){
//有时候输入一些内容
//有时候在这输出一些内容
}
private static void f(不变的量,变的量形成的参数){
if(){}//出口
return f()//递推公式
}