单调递增的数字
思路:将数字转换为字符串进行操作;从后往前处理;
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);}
};
监控二叉树
class Solution {
private:int res;int traversal(TreeNode* root){//节点只有三种情况:1、有摄像头;2、有覆盖;3、无覆盖;//空节点标记为有覆盖;//需要从下至上遍历二叉树,因为叶子节点不能有摄像头,会造成浪费;//需要根据左右子节点的情况推导出父节点的情况,采用后序遍历;if(root == NULL) return 2;int left = traversal(root->left);int right = traversal(root->right);//情况1:左或右节点无覆盖,父节点必须有摄像头if(left == 3 || right == 3){res++;return 1;}//情况2:左或右节点有摄像头,父节点有覆盖;if(left == 1 || right == 1) return 2;//情况3:左右节点均有覆盖,则父节点无覆盖if(left == 2 && right == 2) return 3;return -1;}
public:int minCameraCover(TreeNode* root) {res = 0;//情况4,最后根节点无覆盖if(traversal(root) == 3) res++;return res;}
};