LeetCode 265. Paint House II(房子涂色)

原题网址:https://leetcode.com/problems/paint-house-ii/

There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.

The cost of painting each house with a certain color is represented by a n x k cost matrix. For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses.

Note:
All costs are positive integers.

Follow up:
Could you solve it in O(nk) runtime?

方法:动态规划,求出最低成本和次低成本,如果房子的颜色和上一个房子最低成本的颜色相同,则涂上次低成本的颜色,否则涂最低成本的颜色。

这道题不需要我们分别求出与每一个颜色不同的最低成本值,只需要求出最低和次低,就可以有效避免颜色间隔的问题,这是关键。

public class Solution {
    private void find(int[] cost, int[] min, int[] color) {
        color[0] = -1;
        color[1] = -1;
        for(int i=0; i<cost.length; i++) {
            if (color[0] == -1 || cost[i] < min[0]) {
                min[0] = cost[i];
                color[0] = i;
            }
        }
        for(int i=0; i<cost.length; i++) {
            if (i != color[0] && (color[1] == -1 || cost[i] < min[1])) {
                min[1] = cost[i];
                color[1] = i;
            }
        }
    }
    public int minCostII(int[][] costs) {
        if (costs == null || costs.length == 0) return 0;
        int[] minCost = new int[2];
        int[] color = new int[2];
        int[] nextMinCost = new int[2];
        int[] nextColor = new int[2];
        find(costs[0], minCost, color);
        for(int i=1; i<costs.length; i++) {
            for(int j=0; j<costs[i].length; j++) {
                costs[i][j] += j!=color[0] ? minCost[0] : minCost[1];
            }
            find(costs[i], nextMinCost, nextColor);
            int[] t1 = minCost;
            minCost = nextMinCost;
            nextMinCost = t1;
            int[] t2 = color;
            color = nextColor;
            nextColor = t2;
        }
        return minCost[0];
    }
}

可以进一步优化得更简洁:

public class Solution {
    // 求出最低成本和次低成本
    private void mins(int[] cost, int[] min) {
        for(int i=0; i<cost.length; i++) {
            if (i==0 || cost[i] < cost[min[0]]) min[0] = i;
        }
        if (min[0] == 0) min[1] = 1; else min[1] = 0;
        for(int i=0; i<cost.length; i++) {
            if (i != min[0] && cost[i] < cost[min[1]]) min[1] = i;
        }
    }
    
    public int minCostII(int[][] costs) {
        if (costs == null || costs.length == 0) return 0;
        int[] minCost = new int[costs[0].length];
        int[] min = new int[2];
        for(int c=0; c<costs[0].length; c++) {
            minCost[c] = costs[0][c];
        }
        mins(minCost, min);
        for(int h=1; h<costs.length; h++) {
            int[] prevCost = minCost;
            minCost = new int[costs[0].length];
            for(int c=0; c<costs[h].length; c++) {
                if (c != min[0]) minCost[c] = prevCost[min[0]] + costs[h][c];
                else minCost[c] = prevCost[min[1]] + costs[h][c];
            }
            mins(minCost, min);
        }
        return minCost[min[0]];
    }
}

如果不分成两个步骤,即先计算每种颜色的最低成本,在寻找最低成本的两种颜色,就会比较罗嗦:

public class Solution {
    public int minCostII(int[][] costs) {
        if (costs == null || costs.length == 0 || costs[0].length == 0) return 0;
        int n = costs.length;
        int k = costs[0].length;
        int[][] mins = new int[n][2];

        int[][] colors = new int[n][2];
        for(int j=0; j<k; j++) {
            if (mins[0][0] == 0 || costs[0][j] < mins[0][0]) {
                colors[0][0] = j;
                mins[0][0] = costs[0][j];
            }
        }
        for(int j=0; j<k; j++) {
            if (j==colors[0][0]) continue;
            if (mins[0][1] == 0 || costs[0][j] < mins[0][1]) {
                colors[0][1] = j;
                mins[0][1] = costs[0][j];
            }
        }
        for(int i=1; i<n; i++) {
            // generate minimum
            for(int j=0; j<k; j++) {
                if (j!=colors[i-1][0]) {
                    if (mins[i][0] == 0 || mins[i-1][0] + costs[i][j] < mins[i][0]) {
                        colors[i][0] = j;
                        mins[i][0] = mins[i-1][0] + costs[i][j];
                    }
                } else {
                    if (mins[i][0] == 0 || mins[i-1][1] + costs[i][j] < mins[i][0]) {
                        colors[i][0] = j;
                        mins[i][0] = mins[i-1][1] + costs[i][j];
                    }
                }
                
            }
            // generate second minimum
            for(int j=0; j<k; j++) {
                if (j==colors[i][0]) continue;
                if (j!=colors[i-1][0]) {
                    if (mins[i][1] == 0 || mins[i-1][0] + costs[i][j] < mins[i][1]) {
                        colors[i][1] = j;
                        mins[i][1] = mins[i-1][0] + costs[i][j];
                    }
                } else {
                    if (mins[i][1] == 0 || mins[i-1][1] + costs[i][j] < mins[i][1]) {
                        colors[i][1] = j;
                        mins[i][1] = mins[i-1][1] + costs[i][j];
                    }
                }
            }
        }
        return mins[n-1][0];
    }
}


B. Array Recoloring time limit per test2 seconds memory limit per test256 megabytes You are given an integer array a of size n . Initially, all elements of the array are colored red. You have to choose exactly k elements of the array and paint them blue. Then, while there is at least one red element, you have to select any red element with a blue neighbor and make it blue. The cost of painting the array is defined as the sum of the first k chosen elements and the last painted element. Your task is to calculate the maximum possible cost of painting for the given array. Input The first line contains a single integer t (1≤t≤103 ) — the number of test cases. The first line of each test case contains two integers n and k (2≤n≤5000 ; 1≤k<n ). The second line contains n integers a1,a2,…,an (1≤ai≤109 ). Additional constraint on the input: the sum of n over all test cases doesn't exceed 5000 . Output For each test case, print a single integer — the maximum possible cost of painting for the given array. Example InputCopy 3 3 1 1 2 3 5 2 4 2 3 1 3 4 3 2 2 2 2 OutputCopy 5 10 8 Note In the first example, you can initially color the 2 -nd element, and then color the elements in the order 1,3 . Then the cost of painting is equal to 2+3=5 . In the second example, you can initially color the elements 1 and 5 , and then color the elements in the order 2,4,3 . Then the cost of painting is equal to 4+3+3=10 . In the third example, you can initially color the elements 2,3,4 , and then color the 1 -st element. Then the cost of painting is equal to 2+2+2+2=8 . 用cpp解决
最新发布
03-19
### 如何在 VSCode 中安装和配置 LeetCode 插件以及 Node.js 运行环境 #### 安装 LeetCode 插件 在 VSCode 的扩展市场中搜索 `leetcode`,找到官方提供的插件并点击 **Install** 按钮进行安装[^1]。如果已经安装过该插件,则无需重复操作。 #### 下载与安装 Node.js 由于 LeetCode 插件依赖于 Node.js 环境,因此需要下载并安装 Node.js。访问官方网站 https://nodejs.org/en/ 并选择适合当前系统的版本(推荐使用 LTS 版本)。按照向导完成安装流程后,需确认 Node.js 是否成功安装到系统环境中[^2]。 可以通过命令行运行以下代码来验证: ```bash node -v npm -v ``` 上述命令应返回对应的 Node.js 和 npm 的版本号。如果没有正常返回版本信息,则可能未正确配置环境变量。 #### 解决环境路径问题 即使完成了 Node.js 的安装,仍可能出现类似 “LeetCode extension needs Node.js installed in environment path” 或者 “command ‘leetcode.toggleLeetCodeCn’ not found” 的错误提示[^3]。这通常是因为 VSCode 未能识别全局的 Node.js 路径或者本地安装的 nvm 默认版本未被正确加载[^4]。 解决方法如下: 1. 手动指定 Node.js 可执行文件的位置 在 VSCode 设置界面中输入关键词 `leetcode`,定位至选项 **Node Path**,将其值设为实际的 Node.js 安装目录下的 `node.exe` 文件位置。例如:`C:\Program Files\nodejs\node.exe`。 2. 使用 NVM 用户管理工具调整默认版本 如果通过 nvm 工具切换了不同的 Node.js 版本,请确保设置了默认使用的版本号。可通过以下指令实现: ```bash nvm alias default <version> ``` 重新启动 VSCode 后测试功能键是否恢复正常工作状态。 --- #### 配置常用刷题语言 最后一步是在 VSCode 设置面板中的 LeetCode 插件部分定义个人习惯采用的主要编程语言作为默认提交方式之一。这样可以减少频繁修改编码风格的时间成本。 --- ### 总结 综上所述,要在 VSCode 上顺利启用 LeetCode 插件及其关联服务,除了基本插件本身外还需额外准备支持性的后台框架——即 Node.js 应用程序引擎;同时针对特定场景下产生的兼容性障碍采取针对性措施加以修正即可达成目标[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值