- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 44 lines of C++ from the credited upstream file 2313.cpp.
- The implementation visibly relies on sequence storage, hash lookup, cached states.
- 1 loop block detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int minimumFlips(TreeNode* root, bool result) {4 return dp(root, result);5 }6 7 private:8 struct PairHash {9 template <class T1, class T2>10 std::size_t operator()(const std::pair<T1, T2>& p) const {11 return std::hash<T1>{}(p.first) ^ std::hash<T2>{}(p.second);12 }13 };14 15 unordered_map<pair<TreeNode*, bool>, int, PairHash> mem;16 17 18 int dp(TreeNode* root, bool target) {19 const pair<TreeNode*, bool> key{root, target};20 if (const auto it = mem.find(key); it != mem.cend())21 return it->second;22 if (root->val == 0 || root->val == 1) 23 return root->val == target ? 0 : 1;24 if (root->val == 5) 25 return dp(root->left == nullptr ? root->right : root->left, !target);26 27 vector<pair<int, int>> nextTargets;28 if (root->val == 2) 29 nextTargets = target ? vector<pair<int, int>>{{0, 1}, {1, 0}, {1, 1}}30 : vector<pair<int, int>>{{0, 0}};31 else if (root->val == 3) 32 nextTargets = target ? vector<pair<int, int>>{{1, 1}}33 : vector<pair<int, int>>{{0, 0}, {0, 1}, {1, 0}};34 else 35 nextTargets = target ? vector<pair<int, int>>{{0, 1}, {1, 0}}36 : vector<pair<int, int>>{{0, 0}, {1, 1}};37 38 int ans = INT_MAX;39 for (const auto& [leftTarget, rightTarget] : nextTargets)40 ans = min(ans, dp(root->left, leftTarget) + dp(root->right, rightTarget));41 return mem[key] = ans;42 }43};44