C++ 0120.cpp
class Solution {
map<pair<int,int>, int> cache;
int dp(const vector<vector<int>>& tri, int r, int c)
{
if (r == tri.size())
return 0;
auto lookup = cache.find({r,c});
if (lookup != cache.end())
return lookup->second;
int a = tri[r][c] + dp(tri, r+1, c);
int b = tri[r][c] + dp(tri, r+1, c+1);
int result = a < b ? a : b;
cache[{r,c}] = result;
return result;
}
public:
int minimumTotal(vector<vector<int>>& triangle) {
cache.clear();
return dp(triangle, 0,0);
}
};
Difficulty
and has an acceptance rate of about 60% (2+ million submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The presented implementation solves the classic “minimum path sum in a triangle” problem. It employs a depth-first recursion that explores the two possible moves from each element-downward and down-right-while caching intermediate results to avoid redundant work. The public interface clears any prior state and initiates the recursive process from the apex of the triangle.
Core Logic
The heart of the solution resides in the private dp method. It receives the triangle, a row index r, and a column index c. The first conditional checks whether the recursion has stepped past the last row; reaching this condition signals that no further contribution to the path sum is possible, so the method returns 0.
int dp(const vector<vector<int>>& tri, int r, int c)
{
if (r == tri.size())
return 0;
Next, the method attempts to retrieve a previously computed value from the cache. The cache key is a pair<int,int> representing the current coordinates. If the key exists, the stored result is returned immediately, bypassing further recursion.
auto lookup = cache.find({r,c});
if (lookup != cache.end())
return lookup->second;
When a cache miss occurs, the algorithm proceeds to evaluate the two permissible moves. The value at the current cell tri[r][c] is added to the result of recursing to the element directly below (r+1, c) and to the element down-right (r+1, c+1). The smaller of the two sums is selected as the optimal continuation from the current position.
int a = tri[r][c] + dp(tri, r+1, c);
int b = tri[r][c] + dp(tri, r+1, c+1);
int result = a < b ? a : b;
Finally, the computed result is stored in the cache under the current coordinate pair, ensuring that any future request for the same sub-problem can be satisfied instantly. The method then returns the cached value.
cache[{r,c}] = result;
return result;
}
Entry Point
The public minimumTotal method prepares the environment for a fresh computation. It clears the cache to guarantee that no stale entries from a previous invocation interfere with the current run. Afterwards, it launches the recursive exploration from the top of the triangle (row 0, column 0) and returns the final minimum path sum.
int minimumTotal(vector<vector<int>>& triangle) {
cache.clear();
return dp(triangle, 0,0);
}
Edge Cases Handled
The base-case condition if (r == tri.size()) return 0; gracefully handles the scenario where recursion reaches beyond the bottom row, effectively terminating the path. This also covers the situation of an empty triangle: the initial call to dp receives r == 0 and tri.size() == 0, causing an immediate return of 0.
Because the algorithm always accesses tri[r][c] and tri[r][c+1] only when r is strictly less than tri.size(), it never indexes out of bounds. The triangular structure guarantees that each row r contains exactly r+1 elements, making both c and c+1 valid indices for the recursive calls.
The implementation also works correctly when triangle entries are negative, zero, or positive, as the comparison a < b ? a : b selects the numerically smaller sum without any assumptions about sign.
Performance Optimizations
Memoization is the primary optimization technique employed. By storing each sub-problem result in a map<pair<int,int>, int>, the algorithm eliminates the exponential blow-up typical of naïve recursive solutions. Each distinct coordinate pair is evaluated at most once, turning the overall work into a linear scan over the triangle’s cells.
The explicit cache.clear() at the start of minimumTotal ensures that the map does not retain entries across multiple calls, preventing unnecessary memory growth and guaranteeing that each invocation works with a clean slate.
Using a map provides logarithmic-time lookup and insertion, which is sufficient for the problem size and keeps the implementation straightforward. The early return on the base case prevents deeper recursion once the bottom of the triangle is reached, reducing call-stack depth and associated overhead.
ELI5 - Simplified Explanation
Imagine you have a giant pyramid made of blocks, and you want to walk from the very top down to the bottom. Each block has a special number inside it, and as you step on a block, you add that number to your collection. The goal is to reach the bottom while keeping the total sum of your numbers as small as possible.
To do this, you stand at the top and look at the path ahead. Every time you are on a block, you have two choices: you can step down to the left or step down to the right. This code acts like a smart helper that remembers the best way to get to the bottom from any block where you have already been.
The map acts like a notebook where the helper writes down the smallest total sum it found for each spot. Before the helper calculates the math for a spot, it checks the notebook to see if it has been there before. If the answer is already written down, it just uses that instead of doing all the hard work again.
When the helper stands on a block, it adds the current block number to the result of exploring both the left path and the right path. It picks the path that gives the smaller total. By using the notebook to remember these results, the helper saves lots of time and finds the shortest way through the pyramid very quickly.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||||
| WalkCCC | C++ | Python | Java | |||||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | TS | ||||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | aylei | Rust | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | Python | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| martianoff | Scala | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| withaarzoo | C++ | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | Python, Python | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| martianoff | Scala | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| withaarzoo | C++ | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality