Approach
Depth-first search
For Minimum Increments to Equalize Leaf Paths, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 87 lines of C++ from the credited upstream file minimum-increments-to-equalize-leaf-paths.cpp.
- The implementation visibly relies on sequence storage.
- 6 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 int minIncrease(int n, vector<vector<int>>& edges, vector<int>& cost) {8 vector<vector<int>> adj(n);9 for (const auto& e : edges) {10 adj[e[0]].emplace_back(e[1]);11 adj[e[1]].emplace_back(e[0]);12 }13 const auto& iter_dfs = [&]() {14 int result = n - 1;15 vector<int64_t> mx(n);16 vector<tuple<int, int, int>> stk = {{1, 0, -1}};17 while (!empty(stk)) {18 const auto [step, u, p] = stk.back(); stk.pop_back();19 if (step == 1) {20 stk.emplace_back(2, u, p);21 for (const auto& v : adj[u]) {22 if (v == p) {23 continue;24 }25 stk.emplace_back(1, v, u);26 }27 } else if (step == 2) {28 int cnt = 0;29 for (const auto& v : adj[u]) {30 if (v == p || mx[v] < mx[u]) {31 continue;32 }33 if (mx[v] > mx[u]) {34 mx[u] = mx[v];35 cnt = 0;36 }37 ++cnt;38 }39 result -= cnt;40 mx[u] += cost[u];41 }42 }43 return result;44 };45 46 return iter_dfs();47 }48};49 50515253class Solution2 {54public:55 int minIncrease(int n, vector<vector<int>>& edges, vector<int>& cost) {56 vector<vector<int>> adj(n);57 for (const auto& e : edges) {58 adj[e[0]].emplace_back(e[1]);59 adj[e[1]].emplace_back(e[0]);60 }61 int result = n - 1;62 const function<int64_t (int, int)> dfs = [&](int u, int p) {63 int64_t mx = 0;64 int cnt = 0;65 for (const auto& v : adj[u]) {66 if (v == p) {67 continue;68 }69 const auto& c = dfs(v, u);70 if (c < mx) {71 continue;72 }73 if (c > mx) {74 mx = c;75 cnt = 0;76 }77 ++cnt;78 }79 result -= cnt;80 return mx + cost[u];81 };82 83 dfs(0, -1);84 return result;85 }86};87