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 :
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- 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
- Maximum path sum in an Inverted triangle | SET 2
- Minimum height of a triangle with given base and area
- Minimum Sum Path In 3-D Array
- Minimum odd cost path in a matrix
- Minimum sum falling path in a NxN grid
- Find the minimum difference path from (0, 0) to (N-1, M-1)
- Minimum cost path in a Matrix by moving only on value difference of X
- Minimum Cost Path with Left, Right, Bottom and Up moves allowed
- Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree
- Biggest Reuleaux Triangle within a Square which is inscribed within a Right angle Triangle
- Minimum Numbers of cells that are connected with the smallest path between 3 given cells
- Biggest Reuleaux Triangle inscribed within a Square inscribed in an equilateral triangle
- Hosoya's Triangle
- Sierpinski triangle
- Find Perimeter of a triangle
- Area of Reuleaux Triangle
- Find all angles of a given triangle
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.