📜  三角形中的最大路径和。

📅  最后修改于: 2021-09-22 09:55:58             🧑  作者: Mango

我们以三角形的形式给出了数字,从三角形的顶部开始,移动到下一行的相邻数字,从上到下找到最大的总数。
例子 :

Input : 
   3
  7 4
 2 4 6
8 5 9 3
Output : 23
Explanation : 3 + 7 + 4 + 9 = 23 

Input :
   8
 -4 4
 2 2 6
1 1 1 1
Output : 19
Explanation : 8 + 4 + 6 + 1 = 19 

我们可以通过检查每条可能的路径来解决蛮力问题,但这需要很多时间,所以我们应该尝试借助动态规划来解决这个问题,从而降低时间复杂度。
如果我们应该左移每个元素并在每个空位置放 0 以使其成为常规矩阵,那么我们的问题看起来像最小成本路径。
因此,在将我们的输入三角形元素转换为正则矩阵后,我们应该应用动态规划概念来找到最大路径和。
以自下而上的方式应用 DP 我们应该将我们的问题解决为:
例子:

3
  7 4
 2 4 6
8 5 9 3

Step 1 :
3 0 0 0
7 4 0 0
2 4 6 0
8 5 9 3

Step 2 :
3  0  0  0
7  4  0  0
10 13 15 0

Step 3 :
3  0  0  0
20 19 0  0

Step 4:
23 0 0 0

output : 23
C++
// C++ program for Dynamic
// Programming implementation of
// Max sum problem in a triangle
#include
using namespace std;
#define N 3
 
//  Function for finding maximum sum
int maxPathSum(int tri[][N], int m, int n)
{
     // loop for bottom-up calculation
     for (int i=m-1; i>=0; i--)
     {
        for (int j=0; j<=i; j++)
        {
            // for each element, check both
            // elements just below the number
            // and below right to the number
            // add the maximum of them to it
            if (tri[i+1][j] > tri[i+1][j+1])
                tri[i][j] += tri[i+1][j];
            else
                tri[i][j] += tri[i+1][j+1];
        }
     }
 
     // return the top element
     // which stores the maximum sum
     return tri[0][0];
}
 
/* Driver program to test above functions */
int main()
{
   int tri[N][N] = {  {1, 0, 0},
                      {4, 8, 0},
                      {1, 5, 3} };
   cout << maxPathSum(tri, 2, 2);
   return 0;
}


Java
// Java Program for Dynamic
// Programming implementation of
// Max sum problem in a triangle
import java.io.*;
 
class GFG {
         
    static int N = 3;
     
    // Function for finding maximum sum
    static int maxPathSum(int tri[][], int m, int n)
    {
        // loop for bottom-up calculation
        for (int i = m - 1; i >= 0; i--)
        {
            for (int j = 0; j <= i; j++)
            {
                // for each element, check both
                // elements just below the number
                // and below right to the number
                // add the maximum of them to it
                if (tri[i + 1][j] > tri[i + 1][j + 1])
                    tri[i][j] += tri[i + 1][j];
                else
                    tri[i][j] += tri[i + 1][j + 1];
            }
        }
     
        // return the top element
        // which stores the maximum sum
        return tri[0][0];
    }
     
    /* Driver program to test above functions */
    public static void main (String[] args)
    {
        int tri[][] = { {1, 0, 0},
                        {4, 8, 0},
                        {1, 5, 3} };
        System.out.println ( maxPathSum(tri, 2, 2));
    }
}
 
// This code is contributed by vt_m


Python3
# Python program for
# Dynamic Programming
# implementation of Max
# sum problem in a
# triangle
 
N = 3
 
# Function for finding maximum sum
def maxPathSum(tri, m, n):
 
    # loop for bottom-up calculation
    for i in range(m-1, -1, -1):
        for j in range(i+1):
 
            # for each element, check both
            # elements just below the number
            # and below right to the number
            # add the maximum of them to it
            if (tri[i+1][j] > tri[i+1][j+1]):
                tri[i][j] += tri[i+1][j]
            else:
                tri[i][j] += tri[i+1][j+1]
 
    # return the top element
    # which stores the maximum sum
    return tri[0][0]
 
# Driver program to test above function
 
tri = [[1, 0, 0],
       [4, 8, 0],
       [1, 5, 3]]
print(maxPathSum(tri, 2, 2))
 
# This code is contributed
# by Soumen Ghosh.


C#
// C# Program for Dynamic Programming
// implementation of Max sum problem
// in a triangle
using System;
 
class GFG {
     
    // Function for finding maximum sum
    static int maxPathSum(int [,]tri,
                          int m, int n)
    {
        // loop for bottom-up calculation
        for (int i = m - 1; i >= 0; i--)
        {
            for (int j = 0; j <= i; j++)
            {
                // for each element,
                // check both elements
                // just below the number
                // and below right to
                // the number add the
                // maximum of them to it
                if (tri[i + 1,j] >
                       tri[i + 1,j + 1])
                    tri[i,j] +=
                           tri[i + 1,j];
                else
                    tri[i,j] +=
                       tri[i + 1,j + 1];
            }
        }
     
        // return the top element
        // which stores the maximum sum
        return tri[0,0];
    }
     
    /* Driver program to test above
    functions */
    public static void Main ()
    {
        int [,]tri = { {1, 0, 0},
                        {4, 8, 0},
                        {1, 5, 3} };
                         
        Console.Write (
             maxPathSum(tri, 2, 2));
    }
}
 
// This code is contributed by nitin mittal.


PHP
= 0; $i--)
    {
        for ($j = 0; $j <= $i; $j++)
        {
            // for each element, check
            // both elements just below
            // the number and below right
            // to the number add the maximum
            // of them to it
            if ($tri[$i + 1][$j] > $tri[$i + 1]
                                       [$j + 1])
                $tri[$i][$j] += $tri[$i + 1][$j];
            else
                $tri[$i][$j] += $tri[$i + 1]
                                    [$j + 1];
        }
    }
 
    // return the top element
    // which stores the maximum sum
    return $tri[0][0];
}
 
// Driver Code
$tri= array(array(1, 0, 0),
            array(4, 8, 0),
            array(1, 5, 3));
echo maxPathSum($tri, 2, 2);
 
// This code is contributed by ajit
?>


Javascript


输出 :

14

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程