递归的概念:
一个方法在执行过程中调用自身, 就称为 “递归”. 递归相当于数学上的 “数学归纳法”, 有一个起始条件, 然后有一个递推公式. 例如, 我们求 N! 起始条件: N = 1 的时候, N! 为 1. 这个起始条件相当于递归的结束条件. 递归公式: 求 N! , 直接不好求, 可以把问题转换成 N! => N * (N-1)!
1、递归求 N 的阶乘
public static void main(String[] args) {
int n = 5;
int ret = factor(n);
System.out.println("ret = " + ret);
}
public static int factor(int n) {
if (n == 1) {
return 1;
}
return n * factor(n - 1);
}
2、
按顺序打印一个数字的每一位(例如 1234 打印出 1 2 3 4)
public static void func(int num) {
if(num > 9) {
func(num / 10);
}
System.out.println(num % 10);
}
public static void main(String[] args) {
func(1234);
}
3、
递归求 1 + 2 + 3 + … + 10
public static int sum (int num) {
if(num == 1) {
return 1;
}
return num + sum(num - 1);
}
public static void main(String[] args) {
System.out.println(sum(10));
}
4、
写一个递归方法,输入一个非负整数,返回组成它的数字之和.
public static int func (int num) {
if(num <= 9) {
return num;
}
return (num % 10) + func(num / 10);
}
public static void main(String[] args) {
func(1234);
System.out.println(func(1234));
}
5、
求斐波那契数列的第 N 项
//用递归写斐波那契数列
public static int fab (int n) {
if(n == 1 || n == 2) {
return 1;
}
return fab(n-1) + fab(n-2);
}
public static void main(String[] args) {
System.out.println(fab(20));
}
//不用递归,用迭代=循环写斐波那契数列
public static int fab (int n) {
int f1 = 1;
int f2 = 1;
int f3 = 1;
for(int i = 3;i <= n;i++) {
f3 = f1 + f2;
f1 = f2;
f2 = f3;
}
return f3;
}
public static void main(String[] args) {
System.out.println(fab(20));
}
6、
一只青蛙一次可以跳上 1 级台阶,也可以跳上2 级。求该青蛙跳上一个n 级的台阶总共有多少种跳法
//青蛙跳台阶 斐波那契数列
public static int fab (int n) {
if(n == 1 || n == 2) {
return n;
}
return fab(n-1) + fab(n-2);
}
public static void main(String[] args) {
System.out.println(fab(4));
}
//青蛙跳台阶非递归
public static int fab (int n) {
int f1 = 1;
int f2 = 2;
int f3 = 1;
if(n == 1 || n == 2) {
return n;
}
for(int i = 3;i <= n;i++) {
f3 = f1 + f2;
f1 = f2;
f2 = f3;
}
return f3;
}
public static void main(String[] args) {
System.out.println(fab(4));
}
7、求解汉诺塔问题
public class Test {
public static void move(char pos1,char pos2) {
System.out.println(pos1 + "->" + pos2);
}
//pos1通过pos2移动到pos3
public static void Hanota(int n,char pos1,char pos2,char pos3) {
if(n == 1) {
move(pos1,pos3);
}
else {
Hanota(n-1,pos1,pos3,pos2);
move(pos1,pos3);
Hanota(n-1,pos2,pos1,pos3);
}
}
public static void main(String[] args) {
int n = 3;
Hanota(n,'A','B','C');
}
}