【贪心算法5】

力扣738.单调递增的数字

链接: link

思路

遇到ci>ci+1则ci--,然后就是给ci+1赋值'9';需要注意的是star初值问题,可见注释部分。

javascript 复制代码
class Solution {
    public int monotoneIncreasingDigits(int n) {
        String s = String.valueOf(n);
        char[] c = s.toCharArray();
        int star = c.length; // 这里初始化必须是c.length,不能为0,因为遇到1234这个测例会出问题
        for (int i = c.length - 2; i >= 0; i--) {
            if (c[i] > c[i + 1]) {
                c[i]--;
                star = i+1; // 记录下一位起始位置
            }
        }
        for(int i = star;i<c.length;i++){
            c[i] = '9';
        }
        return Integer.parseInt(String.valueOf(c));
    }
}

相似题型

思路

设计初衷:叶子节点不放摄像头,让其父节点放

三种状态0-无覆盖;1-有摄像头;2-有覆盖;

注意考虑null节点的状态
详细思路

968.监控二叉树

链接: link

javascript 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode() {}
 * TreeNode(int val) { this.val = val; }
 * TreeNode(int val, TreeNode left, TreeNode right) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
/*
 * 0-无覆盖
 * 1-有摄像头
 * 2-有覆盖
 */
class Solution {
    int res = 0;

    public int minCameraCover(TreeNode root) {
        if (afterorder(root) == 0) {
            res++;
        }
        return res;
    }

    public int afterorder(TreeNode root) {
        if (root == null) {
            return 2;
        }
        // 左
        int left = afterorder(root.left);
        int right = afterorder(root.right);
        // 如果左右节点都覆盖了的话, 中间节点就该为无覆盖
        if (left == 2 && right == 2) {
            return 0;
        } else if (left == 0 || right == 0) {
            // 左右节点都是无覆盖状态,中间节点为有摄像头
            res++;
            return 1;
        } else {
            // 左右节点至少有一个摄像头,中间节点有覆盖
            return 2;
        }
    }
}
相关推荐
硕风和炜20 分钟前
【LeetCode: 1301. 最大得分的路径数目 + DP】
java·算法·leetcode·动态规划·dp·记忆化搜索
用户990450177800933 分钟前
做了一个AI诊断,参考倪海厦中医理论,科学养生
算法
努力中的编程者41 分钟前
STL-vector的模拟实现
开发语言·c++·算法·stl·vector
weixin_400005601 小时前
RL-frenet-trajectory-planning-in-CARLA
人工智能·深度学习·算法·机器学习·自动驾驶
Keven_111 小时前
AcWing算法提高课思路速查:动态规划
算法·动态规划
剑挑星河月1 小时前
94.二叉树的中序遍历
java·算法·leetcode
拳里剑气1 小时前
C++算法:队列与BFS
c++·算法·bfs·宽度优先·队列
Ivanqhz2 小时前
注意力机制
线性代数·算法·矩阵·哈希算法·dnn
z小猫不吃鱼2 小时前
02 Optimal Brain Damage 详解:二阶信息剪枝的起点
算法·机器学习·剪枝
Sw1zzle2 小时前
算法入门(三):二分查找 - 基础模板 & 边界控制(Leetcode 704/35/278/34/69/367)
算法·leetcode