代码随想录算法训练营Day37|738.单调递增的数字、968.监控二叉树

738.单调递增的数字

题目链接:738.单调递增的数字
文档链接:738.单调递增的数字
视频链接:贪心算法,思路不难想,但代码不好写!LeetCode:738.单调自增的数字

C++实现

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

968.监控二叉树

题目链接:968.监控二叉树
文档链接:968.监控二叉树
视频链接:贪心算法,二叉树与贪心的结合,有点难… LeetCode:968.监督二叉树

C++实现

class Solution {
private:
    int result = 0;
    int backtracking(TreeNode* node) {
        if (node == NULL)
            return 2;
        int left = backtracking(node->left);
        int right = backtracking(node->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;
    }

public:
    int minCameraCover(TreeNode* root) {
        result = 0;
        int n = backtracking(root);
        if (n == 0)
            result++;
        return result;
    }
};

你可能感兴趣的:(算法训练,算法)