Digital triangle of DP model digital triangle

Title description

Given a digital triangle as shown in the figure below, starting from the top, at each node, you can choose to move to the node at the bottom left or to the node at the bottom right, and walk to the bottom, asking for a path To maximize the sum of the numbers on the path.

        7
      3   8
    8   1   0
  2   7   4   4
4   5   2   6   5

Input format

The first line contains the integer n, which represents the number of layers of the digital triangle. In the next n rows, each row contains several integers, and the i-th row represents the integer contained in the i-th layer of the digital triangle.

Output format

Output an integer that represents the largest path number sum.
data range

1≤n≤500,10000≤三角形中的整数≤10000

Input sample:

5
7
3 8
8 1 0 
2 7 4 4
4 5 2 6 5

Sample output:

30

Ideas

1.可以通过输入案例知道可以把数据直接看成一
个直角三角形,再结合题意很容易设出状态方程
“dp[i][j]”表示从(1,1)到第i行第j列最大路
径之和;

2.一个当前的数只能由上面或者左上边过来,这
样动态转换方程式大致就出来了
dp[i][j]=Math.max(dp[i-1][j],dp[i-1][j-1])+arr[i][j]3.再考虑一些边界问题,最左边的只能从上面来,
最右边的只能由左上角来。(其实这一步也可以
可以不考虑,拿样例这个输入举个例子,当我们
求dp[2][2]时,我们要知道Math.max(dp[1][1],dp[1][2])
dp[1][2]为肯定不大于dp[1][1];)

4. 从最后一行找最大值,由状态定义可知dp[i][j]
只是表示第i行第j列的最大值,但在第i行里并
不一定是最大值;


Code

import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner input =new Scanner(System.in);
        int N=input.nextInt();

        int [][]dp=new int[N+1][N+1];
        int [][]map=new int[N+1][N+1];
        for(int i=1;i<=N;i++){
    
    
            for(int j=1;j<=i;j++){
    
    
                map[i][j]=input.nextInt();
            }
        }
           for(int i=0;i<=N;i++){
    
    
            for(int j=0;j<=N;j++){
    
    
     
                dp[i][j]=Integer.MIN_VALUE;
            }
        }
        dp[1][1]=map[1][1];
        for(int i=2;i<=N;i++){
    
    
            for(int j=1;j<=i;j++){
    
    
                dp[i][j]=Math.max(dp[i-1][j-1],dp[i-1][j])+map[i][j];

            }
        }
        int max=Integer.MIN_VALUE;
        for(int i=1;i<=N;i++){
    
    
            max=Math.max(max,dp[N][i]);
        }
        System.out.println(max);

    }
}

Guess you like

Origin blog.csdn.net/qq_44844588/article/details/108331002