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 path sum in an Inverted triangle | SET 2
- Maximum sum of a path in a Right Number Triangle
- Minimum Sum Path In 3-D Array
- Minimum odd cost path in a matrix
- Minimum sum falling path in a NxN grid
- Minimum height of a triangle with given base and area
- Minimum Cost Path with Left, Right, Bottom and Up moves allowed
- Minimum Numbers of cells that are connected with the smallest path between 3 given cells
- Biggest Reuleaux Triangle within a Square which is inscribed within a Right angle Triangle
- Biggest Reuleaux Triangle inscribed within a Square inscribed in an equilateral triangle
- Min Cost Path | DP-6
- Check for possible path in 2D matrix
- C Program for Min Cost Path
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.