
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Evaluate Reverse Polish Notation in C++
Suppose we have a triangle. We have to find the minimum path sum from top to the bottom. In each step we can move to adjacent numbers on the row below.
For example, if the following triangle is like
[ [2], [3,4], [6,5,7], [4,1,8,3] ]
The minimum path sum from top to bottom is 11 (2 + 3 + 5 + 1 = 11).
Let us see the steps
- Create one table to use in Dynamic programming approach.
- n := size of triangle
- for i := n – 2 down to 0
- for j := 0 to i
- dp[j] := triangle[i, j] + minimum of dp[j] and dp[j + 1]
- for j := 0 to i
- return dp[0]
Let us see the following implementation to get better understanding
Example
class Solution { public: void printVector(vector <int>& v){ for(int i = 0; i < v.size(); i++)cout << v[i] << " "; cout << endl; } int minimumTotal(vector<vector<int>>& triangle) { vector <int> dp(triangle.back()); int n = triangle.size(); for(int i = n - 2; i >= 0; i--){ for(int j = 0; j <= i; j++){ dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]); } // printVector(dp); } return dp[0]; } };
Input
[[2],[3,4],[6,5,7],[4,1,8,3]]
Output
11
Advertisements