贪心的关键在于能否通过局部最优推出全局最优
738. 单调递增的数字
class Solution {
public:
// to_string() stoi()
int monotoneIncreasingDigits(int n) {
string strNum = to_string(n);
int flag = strNum.size();
for (int i = strNum.size() - 1; i > 0; i--) {
if (strNum[i] >= strNum[i - 1]) {
continue;
}
else {
strNum[i - 1] -= 1;
flag = i;
}
}
for (int i = flag; i < strNum.size(); ++i) {
strNum[i] = '9';
}
return stoi(strNum);
}
};
968. 监控二叉树
还是没有怎么看懂这道题目,可能需要回过头去理解二叉树的相关知识
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
int result;
int traversal(TreeNode* cur) {
if (cur == NULL) return 2;
int left = traversal(cur->left); // 左
int right = traversal(cur->right); // 右
if (left == 2 && right == 2) return 0;
else if (left == 0 || right == 0) {
result++;
return 1;
} else return 2;
}
public:
int minCameraCover(TreeNode* root) {
result = 0;
if (traversal(root) == 0) { // root 无覆盖
result++;
}
return result;
}
};