Dynamic Planning Special 2-- digital triangle shortest path problem

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_44771588/article/details/102697554

First, the problem : Figure
Here Insert Picture Description
II Analysis : Each integer can only start to move down to the adjacent integer. Obviously if it is from top to bottom, then the path will be a lot. This time we used the idea of dynamic programming, bottom-up. From the bottom up to the top floor, so in the end a [0] [0] is the answer.
So how do you express it? 1, then the penultimate line array from a start adder 2, to give a [0] [0] results. Two-step, easy.
Third, the code : the following

int a[100][100] =
{
	{2},
	{3,4},
	{6,5,7},
	{8,3,9,2}
};
void solve()
{
	int n = 4;//4是最后一行的列数,这样写不太明智
	for(int i = n - 2; i >= 0; i++)//倒数第二行开始往上走
		for(int j = 0; j <= i; j++)//元素个数等于行数的大小
		{
//下面代码也就是a[i][j] = a[i][j] + min(a[i+1][j], a[i+1][j+1])
			if(a[i+1][j] > a[i+1][j+1])
				a[i][j] += a[i+1][j];
			else
				a[i][j] += a[i+1][j];
		}

	printf("%d\n",a[0][0])
}
void main()
{
	sovle();
}

Guess you like

Origin blog.csdn.net/weixin_44771588/article/details/102697554