Dynamic Programming--Digital Triangle

Problem description: Digital triangle problem

                       7

                 3         9

            8        2        8

      4        7        6        7

2         5      4         3        5

    Find a path from top to bottom in the number triangle above such that the numbers passed on the path only sum to the maximum.

Each step on the path can only go down left or down right. It is only necessary to ask for this maximum sum, and it is not necessary to give a specific path.

Input format:

4 //Number of triangle rows. Below is the triangle

7

3    8

8    1    0

2    7    4    4

Topic Analysis:

    The first idea we think of for this problem is to solve it recursively, but after careful analysis, if the given number of rows n is relatively large, then the time complexity will reach 2^n order, as you can imagine, this is very large, And it involves double counting. Therefore, we can use the idea of ​​dynamic programming to solve the problem and reduce the time complexity by sacrificing space. Here, a two-dimensional array is applied to store the calculated values.

The specific code is as follows:

#include<stdio.h>
#define Max 6
int maxSum[Max][Max]; //Store the value corresponding to the triangle element to the bottom
int n;
int D[Max][Max];

int max(int x,int y ){
	return x>=y?x:y;
}

int main(){
	int i,j;
	scanf("%d",&n);
	for(i=1;i<=n;i++)
		for(j=1;j<=i;j++)
			scanf("%d",&D[i][j]);
	for(i=1;i<=n;i++)
		maxSum[n][i] = D[n][i];//The value from the last row to the bottom is equal to the value corresponding to the bottom row of the triangle
	for(i=n-1;i>=1;i--)
		for(j=1;j<=i;j++)
			maxSum [i] [j] = max (maxSum [i + 1] [j], maxSum [i + 1] [j + 1]) + D [i] [j]; //
	printf("%d",maxSum[1][1]);
}
 

The time complexity of the above program is O(n^2)

The test is as follows:


 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326560132&siteId=291194637