Simple to understand recursion

Recursive design experience

	1.找重复(子问题)
	2.找重复中的变化量-->参数
	3.找参数变化趋势-->设计出口

Recursive basic training

Factorial

	private static int f1(int n) {
		if (n == 1) {
			return 1;
		}
		
		return n * f1(n - 1);
	}

Print i ~ j

	private static void f2(int i, int j) {
		if (i > j) {
			System.out.println();
			return;
		}
		System.out.print(i + " ");
		f2(i + 1, j);

	}

Sum of all the elements of an array

	private static int f3(int[] a, int begin) {
		//begin等于最后一个元素下标
		if (begin == a.length - 1) {
			return a[begin];
		}

		return a[begin] + f3(a, begin + 1);
	}

Flip string

	private static String f4(String str, int end) {
		if (end == 0) {
			return str.charAt(0) + "";
		}

		return str.charAt(end) + f4(str, end - 1);

	}

Multi-branch recursive: Fibonacci number

    等价于两个子问题:
        求前一项
        求前二项
        两项求和
	private static int fib(int n) {
		if (n == 1 || n == 2) {
			return 1;
		}

		return fib(n - 1) + fib(n - 2);
	}

Solving the greatest common divisor with recurrence formula

	private static int gcd(int m, int n) {
		if (n == 0) {
			return m;
		}

		return gcd(n, m % n);
	}

The main function

	public static void main(String[] args) {
		System.out.println(f1(4));
		System.out.println("-------------");
		f2(1, 10);
		System.out.println("-------------");
		System.out.println(f3(new int[]{1,2,3,4,5},0));
		System.out.println("-------------");
		System.out.println(f4("abcd",3));
		System.out.println("-------------");
		System.out.println(fib(6));
		System.out.println("-------------");
		System.out.println(gcd(9,6));
		System.out.println("-------------");
	}
Published 60 original articles · won praise 4 · Views 1289

Guess you like

Origin blog.csdn.net/qq_43966129/article/details/104951397