八. java数据结构 - 递归(1)-概述

154 阅读1分钟

1. 递归的概念

简单的说: 递归就是方法自己调用自己,每次调用时传入不同的变量.递归有助于编程者解决复杂的问题,同时 可以让代码变得简洁。

2.递归调用机制

递归调用机制

3.代码演示

3.1打印问题

    public static void test(int n) {
            if (n > 2) {
                test(n - 1);
            } 
            System.out.println("n=" + n);
    }

	//测试
	public static void main(String[] args) {
		//通过打印问题,回顾递归调用机制
		test(4);
	}

3.2阶乘问题

	public static int factorial(int n) {
		if (n == 1) { 
			return 1;
		} else {
			return factorial(n - 1) * n; // 1 * 2 * 3
		}
	}

	public static void main(String[] args) {
		int res = factorial(3);
		System.out.println("res=" + res);
	}