The understanding of the recursive process

The introduction of a classic recursion problem:
Here Insert Picture Description
code shows:

#include <iostream>
#include <algorithm> //引入算法库
int maxsum(int i, int j);
using namespace std;
int n;//定义总行数
const int index = 100;
int a[100][100];
int main()
{
	cout << "请输入三角形" << endl;
	int i,j;
	cin >> n;
	for(i=1;i<=n;i++)
		for (j = 1;j <= i; j++)
		{
			//a[i][j] << cin;  这种不行
			cin >> a[i][j];
		}
	cout <<maxsum(1,1)<<endl;
	return 0;
	
}
int maxsum(int i, int j)
{
	if (i == n)
		return a[i][j];
		int x = maxsum(i + 1, j);//理解递归问题很关键
		int y = maxsum(i + 1, j + 1);
	return max(x,y) + a[i][j];

}

Understood:
When calling maxsum (1,1), into the subroutine, the subroutine this time will enter the subroutine, when i = 2, j = 1; then again enters the subroutine, when i = 3, j = 1; returns a value [3] [1] to x (x when i = 2, j = x 1 at), noted at the i = 2, j = 1 case , after operation y = xxxx statement, recursive step by step, to get the final solution;

Published 23 original articles · won praise 17 · views 4181

Guess you like

Origin blog.csdn.net/qq_43786066/article/details/104214097