递归基础
1、递归概念
递归是一种方法(函数)调用自己的编程技术
void f(int n){
if(n == 0) //设置出口
return;
f(n - 1); //调用自己
}
2、用递归求阶乘
/*
* 求n的阶乘
* 找重复:n的阶乘 = n * [(n - 1)的阶乘],(n - 1)的阶乘 = (n - 1) * [(n - 2)的阶乘]……
* 找变化:变化的量应该做为参数
* 找边界:出口
*/
public class Myclass {
public static int f1(int n){
if(n == 1)
return 1;
return n * f1(n - 1);
}
public static void main(String[] args) {
System.out.println(f1(5));
}
}
输出结果
120
3、打印 i ~ j
/*
* 找重复:
* 找变化:变化的量应该做为参数
* 找边界:出口
*/
public class Myclass {
public static void f2(int i, int j){
if(i > j)
return;
System.out.println(i);
f2(i + 1, j);
}
public static void main(String[] args) {
f2(1, 5);
}
}
输出结果
1
2
3
4
5
4、数组求和
/*
* 数组求和
* 找重复:
* 找变化:变化的量应该做为参数
* 找边界:出口
*/
public class Myclass {
public static int f3(int[] arr, int index) {
if (index == arr.length - 1)
return arr[index];
return arr[index] + f3(arr, index + 1);
}
public static void main(String[] args) {
int tmp = f3(new int[] { 1, 2, 3, 4, 5 }, 0)
System.out.println(tmp);
}
}
输出结果
15
5、翻转字符串
/*
* 翻转字符串
* 找重复:
* 找变化:变化的量应该做为参数
* 找边界:出口
*/
public class Myclass {
public static String f4(String str, int index){
if(index == 0)
return str.charAt(0) + "";
return str.charAt(index) + f4(str, index - 1);
}
public static void main(String[] args) {
System.out.println(f4("abcdef",5));
}
}
输出结果
fedcba
本篇总结
此篇都是用基础切蛋糕思维实现递归,把一个问题切分为多个小问题,然后逐级击破