
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Evaluate Reverse Polish Notation in C++ Program
- Program to evaluate Postfix Notation in C++
- Dot notation vs Bracket notation in JavaScript
- Dot notation in JavaScript
- Cascade notation in Dart Programming
- Prevent scientific notation in matplotlib.pyplot
- Express 5600000 in Scientific notation.
- Sign Magnitude notation
- Pope John Paul II (1920 – 2005) Polish Pope
- Array reverse() vs reverse! in Ruby
- Big Oh Notation (O)
- Little Oh Notation (o)
- What is Postfix Notation?
- String reverse vs reverse! function in Ruby
- Short hand array notation in C/C++

Advertisements