1. 什么是递归
本质上, 将原来的问题, 转化为更小的同一问题
2. 例子分析
假设我们需要对数组进行求和操作 (只是为了更好理解递归程序)
要求如下: 求解从索引为 0 到 n-1 的数组元素和.
分析:
为了能求解从索引为 0 到 n-1 的数组元素和, 可以分解为第 0 个数加上索引从 1 到 n-1 的数组元素和, 如下:
image.PNG
此时求解索引从 1 到 n-1 的数组元素和的规模比求解从索引为 0 到 n-1 的数组元素和要少一个数以此类推, 如下:
image.PNG
.....
最基本问题:
image.PNG
3. 代码实现本例操作
新建一个 package 包名为 Recursion, 然后在该包下新建一个 SumArray 类, 相关代码如下
- package Recursion;
- public class SumArray {
- // 调用
- public static int sum(int[] arr) {
- return sum(arr, 0);//0 索引从 0 开始
- }
- // 递归实现数组相加
- //l 表示索引
- private static int sum(int[] arr, int l) {
- if (l == arr.length)
- return 0;
- return arr[l] + sum(arr, l + 1);
- }
- // 测试
- public static void main(String[] args) {
- int[] nums = {1, 2, 3, 4, 5, 6, 7};
- int value = sum(nums);
- System.out.println(value);
- }
- }
结果为: 28
对上述代码的分析:
image.PNG
总结: 递归函数就是一个函数, 完成一个功能, 自己调用自己.
来源: http://www.jianshu.com/p/c6eda7068307