第八章 贪心算法 part06

56 阅读1分钟

738. Monotone Increasing Digits

An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.

Given an integer n, return the largest number that is less than or equal to n with monotone increasing digits.

题目解析:

  • 前一位如果减1的话,后面的都可以变成9
  • 所以需要从后往前找,找到最后一个需要减1的位置,然后把后面都变成9

代码:

class Solution {
    public int monotoneIncreasingDigits(int n) {
        String str = String.valueOf(n);
        char[] ca = str.toCharArray();
        int prev = 9;
        int idx = ca.length;
        for (int i = ca.length - 1; i >= 0; i--) {
            int cur = ca[i] - '0';
            if (cur > prev) {
                idx = i + 1;
                ca[i] = String.valueOf(cur - 1).charAt(0);
            }
            prev = ca[i] - '0';
        }
        for (int i = idx; i < ca.length; i++) {
            ca[i] = '9';
        }
        return Integer.parseInt(String.valueOf(ca));
    }
}

968. Binary Tree Cameras

You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.

Return the minimum number of cameras needed to monitor all nodes of the tree.

题目解析:

  • 为了使用最少的摄像头,叶子节点不放摄像头
  • 所以从下往上放(后序遍历),每个节点3中状态: 0 - 没覆盖;1 - 有摄像头; 2 - 已覆盖
    • 当左右节点其中有一个为0时,则当前节点必须放置摄像头
    • 当左右节点有一个有摄像头时,代表当前节点已覆盖
    • 当左右节点都已覆盖时,代表当前节点为没覆盖(叶子结点)

代码:

class Solution {
    int min = 0;
    public int minCameraCover(TreeNode root) {
        int status = cameraCover(root);
        if (status == 0) {
            return min + 1;
        }
        return min;
    }

    public int cameraCover(TreeNode root) {
        if (root == null) return 2;
        int left = cameraCover(root.left);
        int right = cameraCover(root.right);
        if (left == 0 || right == 0) {
            min++;
            return 1;
        }
        if (left == 1 || right == 1) {
            return 2;
        }
        if (left == 2 && right == 2) {
            return 0;
        }
        return -1;
    }

}