Given a triangular structure of numbers, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
Input : 2 3 7 8 5 6 6 1 9 3 Output : 11 Explanation : 2 + 3 + 5 + 1 = 11 Input : 3 6 4 5 2 7 9 1 8 6 Output : 10 Explanation : 3 + 4 + 2 + 1 = 10
Naive Approach : Going through the Naive approach by traversing every possible path. But, this is costly. So, use Dynamic Programming here in order to reduce the time complexity.
There are two ways to reach the solution :
1. Memoization – Starting from the top node, traverse recursively with each node, till the pathsum of that node is calculated. And then store the result in an array. But this will take O(N^2) space to maintain the array.
2. Bottom up – Start from the nodes on the bottom row; the min pathsum for these nodes are the values of the nodes themselves. And after that, minimum pathsum at the ith node of kth row would be the minimum of the pathsum of its two children + the node’s value, i.e.:
memo[k][i] = min( memo[k+1][i], memo[k+1][i+1]) + A[k][i];
Simply set memo as a 1D array, and update it
this will be space efficient also :
For the row k :
memo[i] = min( memo[i], memo[i+1]) + A[k][i];
Below is the implementation of above dynamic programming approach :
- Minimum length of the shortest path of a triangle
- Maximum path sum in a triangle.
- Maximum sum of a path in a Right Number Triangle
- Minimum Sum Path In 3-D Array
- Minimum sum falling path in a NxN grid
- Minimum number of stops from given path
- Minimum odd cost path in a matrix
- Minimum height of a triangle with given base and area
- Minimum edges to reverse to make path from a source to a destination
- Minimum Cost Path with Left, Right, Bottom and Up moves allowed
- Minimum increment in the sides required to get non-negative area of a triangle
- Divide an isosceles triangle triangle in two part with ratio of area as n:m
- Minimum cost path from source node to destination node via an intermediate node
- Sum of upper triangle and lower triangle
- Minimum adjacent swaps to move maximum and minimum to corners
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.