From dc1f0c4c0096013799416664894c5194dc7e1f52 Mon Sep 17 00:00:00 2001 From: Yuqian Yang Date: Fri, 28 Feb 2025 23:13:39 +0800 Subject: chore(store): move everything to store. --- store/works/solutions/leetcode/cpp/968.cpp | 63 ++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 store/works/solutions/leetcode/cpp/968.cpp (limited to 'store/works/solutions/leetcode/cpp/968.cpp') diff --git a/store/works/solutions/leetcode/cpp/968.cpp b/store/works/solutions/leetcode/cpp/968.cpp new file mode 100644 index 0000000..c9e6b24 --- /dev/null +++ b/store/works/solutions/leetcode/cpp/968.cpp @@ -0,0 +1,63 @@ +#include + +struct TreeNode +{ + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +#include + +struct Result +{ + // root_camera >= root_monitored >= root_not_monitored + int root_camera; + int root_monitored; + int root_not_monitored; +}; + +class Solution +{ +public: + Result dfs(TreeNode *root) + { + if (root->left == nullptr && root->right == nullptr) + { + return Result{1, 1, 0}; + } + + if (root->left == nullptr || root->right == nullptr) + { + TreeNode *child_node = root->left == nullptr ? root->right : root->left; + Result child = dfs(child_node); + + int root_camera = 1 + child.root_not_monitored; + int root_monitored = std::min({child.root_camera, + root_camera}); + int root_not_monitored = std::min(child.root_monitored, root_monitored); + + return Result{ + root_camera, root_monitored, root_not_monitored}; + } + + Result left = dfs(root->left); + Result right = dfs(root->right); + + int root_camera = 1 + left.root_not_monitored + right.root_not_monitored; + int root_monitored = std::min({left.root_camera + right.root_monitored, + left.root_monitored + right.root_camera, + root_camera}); + int root_not_monitored = std::min({left.root_monitored + right.root_monitored, root_monitored}); + + return Result{ + root_camera, root_monitored, root_not_monitored}; + } + + int minCameraCover(TreeNode *root) + { + auto result = dfs(root); + return result.root_monitored; + } +}; \ No newline at end of file -- cgit v1.2.3