一、递归问题模板
先解决剩余问题,在缩小规模
function recursion(大规模){
if (end_condition){ // 明确的递归终止条件
end; // 简单情景
}else{ // 在将问题转换为子问题的每一步,解决该步中剩余部分的问题
solve; // 递去
recursion(小规模); // 递到最深处后,不断地归来
}
}
先缩小规模,在解决剩余问题。
function recursion(大规模){
if (end_condition){ // 明确的递归终止条件
end; // 简单情景
}else{ // 先将问题全部描述展开,再由尽头“返回”依次解决每步中剩余部分的问题
recursion(小规模); // 递去
solve; // 归来
}
}
这两个模板都是要根据具体的问题,才可以做出选择。
二、递归典型问题
1、阶乘问题

//阶乘问题
public class Demo1 {
//递归方法
static int f1(int n) {
//[1]找到递归的出口
if(n== 1) {
return 1;
}
//[2]求解剩余步
//[3]缩小问题规模
return n*f1(n-1);
}
//循环
static int f2(int n) {
int result = 1;
while(n > 0) {
result = result * n;
n--;
}
return result;
}
public static void main(String[] args) {
System.out.println(f1(5));
System.out.println(f2(5));
}
}
2、斐波纳契

public class Demo2 {
//求斐波那契第n项,递归法
public static int f1(int n) {
if(n == 1 || n == 2) {
return 1;
}
return f1(n-1) + f1(n - 2);
}
//迭代法
public static int f2(int n) {
int k1 = 1;
int k2 = 1;
int sum = 1;
if(n == 1 || n == 2) {
return k1;
}
for(int i = 3; i <= n; i++) {
sum = k1 + k2;
k1 = k2;
k2 = sum;
}
return sum;
}
public static void main(String[] args) {
for(int i = 1; i < 7; i++) {
System.out.print(f1(i) + " ");
}
for(int i = 1; i < 7; i++) {
System.out.print(f2(i) + " ");
}
}
}
3、杨辉三角

//杨辉三角
public class Demo3 {
//递归算法求杨辉三角第x行、第y列的值
static int f(int x, int y) {
if(x < 1) {
return 0;
}
if(y > x) {
return 0;
}
if(y == 1 || y == x) {
return 1;
}else {
return f(x-1, y-1) + f(x-1,y);
}
}
public static void main(String[] args) {
for(int i = 1; i < 6; i++) {
for(int j = 1; j < 6; j++) {
System.out.print(f(i,j) + " ");
}
System.out.println();
}
}
}
4、汉诺塔

public class Demo4 {
static void move(String s1, String s2) {
System.out.println(s1 + "-->" + s2);
}
//将n个圆盘借助y柱,从x移到z
static void hanoi(int n, String x, String z, String y) {
if(n == 1) {
move(x,z);
return;
}
hanoi(n-1,x,y,z);
move(x,z);
hanoi(n-1,y,z,x);
}
public static void main(String[] args) {
hanoi(3,"A","C","B");
}
}
5、二叉树
递归是一种编程的技巧,想写好递归除了多练习多积累编程经验,没有其他的办法。
