738.单调递增的数字
题目链接:. - 力扣(LeetCode)
文档讲解:代码随想录
视频讲解:贪心算法,思路不难想,但代码不好写!LeetCode:738.单调自增的数字_哔哩哔哩_bilibili
C++代码:
class Solution {
public:
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 - 1] > strNum[i] ) {
flag = i;
strNum[i - 1]--;
}
}
for (int i = flag; i < strNum.size(); i++) {
strNum[i] = '9';
}
return stoi(strNum);
}
};
968.监控二叉树
题目链接:. - 力扣(LeetCode)
文档讲解:代码随想录
视频讲解:贪心算法,二叉树与贪心的结合,有点难...... LeetCode:968.监督二叉树_哔哩哔哩_bilibili
C++代码:
/**
* 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 {
public:
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;
if (left == 0 || right == 0) {
result++;
return 1;
}
if (left == 1 || right == 1) return 2;
return -1;
}
int minCameraCover(TreeNode* root) {
result = 0;
if (traversal(root) == 0) {
result++;
}
return result;
}
};