Day32 贪心专项

738. 单调递增的数字

class Solution {
public:
    int monotoneIncreasingDigits(int n) {
        string n_s = to_string(n);

        int flag = n_s.size();
        for (int i = n_s.size() - 1; i > 0; i--) {
            if (n_s[i] < n_s[i-1]) {
                n_s[i-1]--;
                flag = i;
            }
        }

        for (int i = flag; i < n_s.size(); i++) {
            n_s[i] = '9';
        }

        return stoi(n_s);
    }
};

968. 监控二叉树

class Solution {
private:
    int ret_ = 0;
public:
    /*
        @return: 0(本节点无覆盖),1(本节点有摄像头),2(本节点有覆盖)
        @brief: 空节点应该返回2,从下向上推导
    */
    int traversal(TreeNode* root) {
        if (root == nullptr) return 2;

        int left = traversal(root->left);
        int right = traversal(root->right);

        if (left == 2 && right == 2) return 0;

        if (left == 0 || right == 0) {
            ret_++;
            return 1;
        }

        if (left == 1 || right == 1) return 2;

        return -1;
    }

    int minCameraCover(TreeNode* root) {
        if (traversal(root) == 0) {
            ret_++;
        }
        return ret_;
    }

};

你可能感兴趣的:(算法学习,leetcode,算法,c++,数据结构)