1. Classic Tree DP (3 States with Minimums)
Intuition
dp[node][0] = cost if camera placed at node. dp[node][1] = cost if covered by child. dp[node][2] = cost if covered by parent.
When to apply: Formal Dynamic Programming approach.
Algorithm
- Step 1: Helper dfs(node) returns tuple (d0, d1, d2).
- Step 2: Combine subtree states using min combinations.
- Step 3: Return min(d0, d1) for root.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution { tuple<int, int, int> dfs(TreeNode* node) { if (!node) return {10000, 0, 0}; auto [l0, l1, l2] = dfs(node->left); auto [r0, r1, r2] = dfs(node->right); int d0 = 1 + min({l0, l1, l2}) + min({r0, r1, r2}); int d1 = min({l0 + r0, l0 + r1, l1 + r0}); int d2 = min(l0, l1) + min(r0, r1); return {d0, d1, d2}; }public: int minCameraCover(TreeNode* root) { auto [d0, d1, d2] = dfs(root); return min(d0, d1); }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n)— Computes 3 states per node in O(1). - Space complexity:
O(h)— Call stack bounded by tree height h.