1. Recursive Top-Down DFS
Intuition
Recursively explore both moves (i and i + 1) from the top cell down to the base row.
Algorithm
- Define
solve(r, c). - If
r == n - 1, returntriangle[r][c]. - Return
triangle[r][c] + min(solve(r + 1, c), solve(r + 1, c + 1)).
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution { int solve(int r, int c, const vector<vector<int>>& triangle) { if (r == triangle.size() - 1) return triangle[r][c]; return triangle[r][c] + min(solve(r + 1, c, triangle), solve(r + 1, c + 1, triangle)); }public: int minimumTotal(vector<vector<int>>& triangle) { return solve(0, 0, triangle); }}; int main() { Solution sol; vector<vector<int>> triangle = {{2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3}}; cout << "Min Path: " << sol.minimumTotal(triangle) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^n) - Space complexity:
O(n) call stack