37代码随想录训练营day37|贪心算法part06

1、单调递增的数字

单调递增的数字

class Solution {
public:
    int monotoneIncreasingDigits(int n) {
        string str = to_string(n);
        int index = str.size();
        for (int i = str.size() - 1; i > 0; i--) {
            if (str[i] < str[i - 1]) {
                str[i - 1]--;
                index = i;
            }
        }
        for (int i = index; i < str.size(); i++) {
            str[i] = '9';
        }
        return stoi(str);
    }
};

2、监控二叉树

监控二叉树

/**
 * 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:
    /*三种状态:
     * 0 无覆盖
     * 1 有摄像头
     * 2 有覆盖
     */
    int result = 0;
    int traversal(TreeNode* root) {
        if (root == NULL) return 2;
        int left = traversal(root->left);
        int right = traversal(root->right);
        if (left == 2 && right == 2) {
            root->val = 0;
            return 0;
        }
        if (left == 0 || right == 0) {
            result++;
            return 1;
        } 
        if (left == 1 || right == 1) return 2;
        return -1;
    }
    int minCameraCover(TreeNode* root) {
        if (traversal(root) == 0) result++;
        return result;
    }
};

你可能感兴趣的:(代码随想录训练营,贪心算法,算法,c++,leetcode)