738-单调递增的数字
题目链接:LeetCode-738中等
思考:从后往前遍历字符串,若前面数字>后面数字,前面数字-1,后面数字定为flag,遍历全部字符串,最后把flag全换成9即可。
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-968困难
思考
情况1:
左右节点都有覆盖
if (left == 2 && right == 2) return 0;
情况2:
left == 0 && right == 0 左右节点无覆盖
left == 1 && right == 0 左节点有摄像头,右节点无覆盖
left == 0 && right == 1 左节点有无覆盖,右节点摄像头
left == 0 && right == 2 左节点无覆盖,右节点覆盖
left == 2 && right == 0 左节点覆盖,右节点无覆盖
if (left == 0 || right == 0) {
result++;
return 1;
}
情况3
left == 1 && right == 2 左节点有摄像头,右节点有覆盖
left == 2 && right == 1 左节点有覆盖,右节点有摄像头
left == 1 && right == 1 左右节点都有摄像头
其他情况前段代码均已覆盖
if (left == 1 || right == 1) return 2;
情况4: 无覆盖
if (traversal(root) == 0) { // root 无覆盖
result++;
}
class Solution {
private:
int result;
int traversal(TreeNode* cur){
if(cur==NULL) return 2;
int left=traversal(cur->left);
int right=traversal(cur->right);
//情况1
if(left==2 && right==2) return 0;
//情况2
if(left==0 || right==0){
result++;
return 1;
}
//情况3
if(left==1 || right==1) return 2;
return -1;
}
public:
int minCameraCover(TreeNode* root) {
result=0; //情况4
if(traversal(root)==0){
result++;
}
return result;
}
}
// 精简上面代码
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;
}
};