Thursday, September 10, 2020

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

Example: Given the following triangle (Example taken from leetcode)

[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]

The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).


Approach: Use DP.

         public int MinimumPathInTriangle(IList<IList<int>> triangle)

        {

            if (triangle == null)

            {

                return -1;

            }

            int maxLength = triangle.Count;

            int[] table = new int[maxLength];

            for (int i = 0; i < maxLength; ++i)

            {

                table[i] = triangle[maxLength - 1][i];

            }

            for (int i = maxLength - 2; i >= 0; --i)

            {

                for (int j = 0; j < triangle[i].Count; ++j)

                {

                    table[j] = Math.Min(table[j], table[j + 1]) + triangle[i][j];

                }

            }

            return table[0];

        }

No comments:

Post a Comment