目录
青蛙跳台阶问题
一只青蛙跳台阶,一次可以跳1阶,可以2阶。那么,台阶为n时,有多少种跳法。
一次只能挑一阶或者两阶时。如果只有1阶,那么一共有1种跳法;
如果有2阶,那么一共有2种跳法。如果有n阶时,最后一步青蛙只能从第n-1或者n-2这两种情况往上跳。
f(1) = 1;
f (2)= 2;
f (n) = f(n-1) + f(n-2)
public class Demo {
public static void main(String[] args) {
int a = 5;
System.out.println(qingwa(a));
}
private static int qingwa(int a) {
if (a == 1) {
return 1;
} else if (a == 2) {
return 2;
}else {
return qingwa(a - 1) + qingwa(a - 2);
}
}
}
递归求解汉诺塔问题
public class HanoiTower {
public static void main(String[] args){
hh hhanoi = new hh();
hhanoi.Hanoi(3,"Tower1","Tower2","Tower3");
}
}
class hh {
public void Hanoi(Integer n, String a, String b, String c) {
if (n == 1) {
System.out.println(a + "->" + c);
} else {
Hanoi(n - 1, a, c, b);
System.out.println(a + "->" + c);
Hanoi(n - 1, b, a, c);
}
}
}
递归求斐波那契数列的第 N 项
public class Fib {
public static void main(String[] args) {
int num = 7;
System.out.println(fib(num));
}
public static int fib(int num){
if (num == 1 || num == 2){
return 1;
}
return fib(num - 1) + fib(num -2);
}
}
返回的数字之和
写一个递归方法,输入一个非负整数,返回组成它的数字之和
public class RecursionAdd {
public static void main(String[] args) {
int num = 2022;
System.out.println(recursionAdd(num));
}
public static int recursionAdd(int num){
//小于 10 ,递归终止条件
if (num < 10){
return num;
}
return num % 10 + recursionAdd(num / 10);
}
}
递归打印数字的每一位
按顺序打印一个数字的每一位(例如 1234 打印出 1 2 3 4) (递归)
import java.util.Scanner;
public class num1234 {
public static void printfNum (int num) {
if(num > 9){
printfNum(num / 10);
}
System.out.println(num % 10 + "");
}
public static void main(String[] args) {
System.out.println("请输入数字");
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
System.out.println("数字的每一位依次为");
printfNum(num);
}
}
递归求和
递归求 1 + 2 + 3 + ... + 10
public class RecursionAdd {
public static void main(String[] args) {
int num = 10;
System.out.println(recursionAdd(num));
}
public static int recursionAdd(int num){
//终止条件 num 等于 1的时候终止
if (num == 1){
return 1;
}
return num + recursionAdd(num - 1);
}
}
递归求 N 的阶乘
import java.util.Scanner;
public class Digui {
public static void main(String[] args) {
//使用递归算法计算n的阶乘
Scanner intput = new Scanner(System.in);
System.out.println("请输入n的值:");
int n = intput.nextInt();
int i = getJ(n);
System.out.println(i);
}
public static int getJ(int n){
if (n == 0){
return 1;
}else {
return n*getJ(n-1);
}
}
}