Preliminary understand recursion

Just let recursive solution is more clear, and there is no performance advantage. Better performance cycles under normal circumstances, but will make a recursive solution clearer. The following two functions are the same of factorial method. It is a normal cyclic method, a recursive method.

Note: Because the recursive method calls itself, so when writing recursive method, you must tell it when to stop. So general recursive method generally have two parts (recursively condition part: calls itself part of the baseline conditions: no longer call themselves, stop calling, to avoid infinite loop)

Normal cyclic factorial method:

public static int jiecheng2(int a) {
		//j用来存放阶乘的结果。
		int j = a;
		for(int i = a - 1 ; i >= 1 ; i--) {
			j = j * i;
		}
		//返回所求的阶乘的结果。
		return j;
	}

Recursive factorial method:

public static int jiecheng (int a) {
		if(a > 1) {
			//当传入的a > 1时就继续调用自己。
			//将多层的方法展开后就相当于:
			//return a*(a-1)*(a-2)*(a-3)*...*1
			//相对于循环求阶乘思路是不是更清晰能?
			return a * jiecheng(a - 1);//------递归条件部分:自己调用自己。
		}else {
			//当传入的a = 1时返回1。
			return 1;//------基线条件部分:不再调用自己,停止调用,避免死循环。
		}
	}

Each recursive method which has two parts: the condition part recursive portion baseline conditions +

Guess you like

Origin blog.csdn.net/qq_41152758/article/details/92610721