Recursive story

Once upon a time there was an old monk who was telling the story of a well

Looking dizzy? In fact, the meaning is clear, add parentheses to see

Once upon a time there was an old monk who was telling the story of [Once upon a time there was an old monk who was telling the story of [a well]]

This is recursion

"One well" is the cut-off condition to prevent infinite recursion.
"There used to be an old monk telling the story of ()" is a recursive machine, which is what each layer of recursion must do

If you want to output this kind of "domestic doll"-like text, recursive implementation is the easiest way in code.

1. Recursion in the middle nest doll from left to right

This model can form the result of [left and right sleeve middle], similar to:

void 老和尚讲故事(int 层)
{
	//左边的壳

	//截止条件,不满足就深入一层,否则就是套娃的核,然后脱出左套娃壳,返回并顺序进行右套娃
	if (层 < 1)
	{
		//最中间的核心
		return;
	}
	
	//深入一层

	//右边的壳
	return;
}

Executable code:

#include<stdio.h>
#define 层 layer
#define 老和尚讲故事 laoheshang

void 老和尚讲故事(int)
{
    
    
	printf("从前有个老和尚在讲(");

	//截止条件
	if (< 1)
	{
    
    
		printf("一口井的故事");
		return;
	}

	老和尚讲故事(- 1);

	printf(")的故事");
	return;
}

int main(){
    
    	老和尚讲故事(2);}

Results of the:

从前有个老和尚在讲(从前有个老和尚在讲(从前有 个老和尚在讲(一口井的故事)的故事)的故事

2. Bifurcation search recursion

This can solve the problem of [there are ten steps, one step or two steps , how many ways to go up the stairs?] this "the same mode, different parameters, a comprehensive search" problem:

#include<stdio.h>
#define 层 layer
#define 老和尚讲故事 laoheshang

void 老和尚讲故事(int)
{
    
    
	printf("从前有个老和尚在讲(");
	//满足条件
	if (== 0)
	{
    
    
		printf("一口井");
		//这里应该留一个想要修改的结果……
	}
	//不符合的条件
	if (< 1)
	{
    
    
		return;
	}

	//分叉可能
	老和尚讲故事(- 3);
	老和尚讲故事(- 2);
	老和尚讲故事(- 1);

	printf(")的故事"); 
	return;
}

int main() {
    
     老和尚讲故事(2); }

Output result:

从前有个老和尚在讲(从前有个老和尚在讲(从前有 个老和尚在讲(一口井从前有个老和尚在讲(从前有 个老和尚在讲(从前有个老和尚在讲(从前有个老和 尚在讲(一口井)的故事)的故事

Split it up, which is the result at the end of all satisfying "layer == 0":

从前有个老和尚在讲(从前有个老和尚在讲(从前有个老和尚在讲(一口井
从前有个老和尚在讲(从前有 个老和尚在讲(从前有个老和尚在讲(从前有个老和 尚在讲(一口井)的故事)的故事

3. The loop is written recursively

This type can be written as the result of the Fibonacci number sequence [recursion], but this is "first recursively find the beginning, and then recursively return to the result"

#include<stdio.h>
#define 层 layer
#define 老和尚讲故事 laoheshang

void 老和尚讲故事(int)
{
    
    
	printf("从前有个老和尚在讲");

	//截止条件
	if (< 1)
	{
    
    
		printf("一口井");
		return;
	}
	return 老和尚讲故事(- 1);
	printf("的故事");//实际没有执行到
}

int main(){
    
    	老和尚讲故事(2);}

Results of the:

从前有个老和尚在讲从前有个老和尚在讲从前有个老和尚在讲一口井

In addition, one of the obstacles to my understanding of recursion was that I could use return to call new functions.

Guess you like

Origin blog.csdn.net/sinat_27382047/article/details/105641624