定义:
无限调用自身,每次调用会改变自身的变量,直到变量不再满足条件,停止调用;
例子:
求阶乘:
package wang.recuision;
/**
* @version 1.0
* @auther WangCode
* @date 2021/1/23 12:57
*/
public class Recursion01 {
public static void main(String[] args) {
Factorial factorial = new Factorial();
System.out.println("factorial.factorial(100) = " + factorial.factorial(3));
}
}
class Factorial{
public int factorial(int n){
if (n == 1 || n == 0){
return n;
}else{
return n*factorial(n-1);
}
}
}
求1-100的和
package wang.recuision;
/**
* @version 1.0
* @auther WangCode
* @date 2021/1/22 15:47
*/
public class Recursion {
public static void main(String[] args) {
Sum sum = new Sum();
int sum1 = sum.sum(100);
System.out.println("sum1 = " + sum1);
}
}
class Sum{
public int sum(int x){
if (x==1){
return 1;
}
return x + sum(x-1);
}
}
汉诺塔问题
package wang.recuision;
import java.util.Scanner;
/**
* @version 1.0
* @auther WangCode
* @date 2021/1/23 13:07
*/
public class TowerofHanoi {
private int i =1;
/**
*
* @param n 盘子数目
* @param origin 源塔
* @param assist 借用塔
* @param destination 目的塔
*/
public void hanoi(int n, String origin,String assist,String destination){
if (n == 1){
move(n,origin,destination);
}else{
//将源塔的前n-1个从目的塔移动到借用塔上
hanoi(n-1,origin,destination,assist);
//将源塔的最后一个盘子移动到目的塔上
move(n,origin,destination);
//最后将借用塔上的n-1个盘子移动到目的塔上
hanoi(n-1,assist,origin,destination);
}
}
public void move(int n,String origin,String destination){
System.out.println("第"+i+++"步:"+n+"号盘子"+origin+"------->"+destination);
}
public static void main(String[] args) {
//输入盘子数
System.out.println("请输入盘子数:");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
TowerofHanoi hanoi = new TowerofHanoi();
hanoi.hanoi(n, "A", "B","C");
}
}