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.

Example:

Input: [[1,5,3],[2,9,4]]
Output: 5
Explanation: Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5;
  Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5.

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

这道题是之前那道 Paint House 的拓展,那道题只让用红绿蓝三种颜色来粉刷房子,而这道题让用k种颜色,这道题不能用之前那题的解法,会 TLE。这题的解法的思路还是用 DP,但是在找不同颜色的最小值不是遍历所有不同颜色,而是用 min1 和 min2 来记录之前房子的最小和第二小的花费的颜色,如果当前房子颜色和 min1 相同,那么用 min2 对应的值计算,反之用 min1 对应的值,这种解法实际上也包含了求次小值的方法,感觉也是一种很棒的解题思路,参见代码如下:

解法一:

class Solution {
public:
int minCostII(vector<vector<int>>& costs) {
if (costs.empty() || costs[].empty()) return ;
vector<vector<int>> dp = costs;
int min1 = -, min2 = -;
for (int i = ; i < dp.size(); ++i) {
int last1 = min1, last2 = min2;
min1 = -; min2 = -;
for (int j = ; j < dp[i].size(); ++j) {
if (j != last1) {
dp[i][j] += last1 < ? : dp[i - ][last1];
} else {
dp[i][j] += last2 < ? : dp[i - ][last2];
}
if (min1 < || dp[i][j] < dp[i][min1]) {
min2 = min1; min1 = j;
} else if (min2 < || dp[i][j] < dp[i][min2]) {
min2 = j;
}
}
}
return dp.back()[min1];
}
};

下面这种解法不需要建立二维 dp 数组,直接用三个变量就可以保存需要的信息即可,参见代码如下:

解法二:

class Solution {
public:
int minCostII(vector<vector<int>>& costs) {
if (costs.empty() || costs[].empty()) return ;
int min1 = , min2 = , idx1 = -;
for (int i = ; i < costs.size(); ++i) {
int m1 = INT_MAX, m2 = m1, id1 = -;
for (int j = ; j < costs[i].size(); ++j) {
int cost = costs[i][j] + (j == idx1 ? min2 : min1);
if (cost < m1) {
m2 = m1; m1 = cost; id1 = j;
} else if (cost < m2) {
m2 = cost;
}
}
min1 = m1; min2 = m2; idx1 = id1;
}
return min1;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/265

类似题目:

Product of Array Except Self

Sliding Window Maximum

Paint House

Paint Fence

参考资料:

https://leetcode.com/problems/paint-house-ii/

https://leetcode.com/problems/paint-house-ii/discuss/69509/Easiest-O(1)-space-JAVA-solution

https://leetcode.com/problems/paint-house-ii/discuss/69492/AC-Java-solution-without-extra-space

https://leetcode.com/problems/paint-house-ii/discuss/69495/Fast-DP-Java-solution-Runtime-O(nk)-space-O(1)

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Paint House II 粉刷房子之二的更多相关文章

  1. [LintCode] Paint House II 粉刷房子之二

    There are a row of n houses, each house can be painted with one of the k colors. The cost of paintin ...

  2. [LeetCode] 265. Paint House II 粉刷房子

    There are a row of n houses, each house can be painted with one of the k colors. The cost of paintin ...

  3. [leetcode]265. Paint House II粉刷房子(K色可选)

    There are a row of n houses, each house can be painted with one of the k colors. The cost of paintin ...

  4. [LeetCode] Flip Game II 翻转游戏之二

    You are playing the following Flip Game with your friend: Given a string that contains only these tw ...

  5. [LeetCode] Word Pattern II 词语模式之二

    Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...

  6. [LeetCode] Ugly Number II 丑陋数之二

    Write a program to find the n-th ugly number. Ugly numbers are positive numbers whose prime factors ...

  7. [LeetCode] Strobogrammatic Number II 对称数之二

    A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside ...

  8. [LeetCode] Basic Calculator II 基本计算器之二

    Implement a basic calculator to evaluate a simple expression string. The expression string contains ...

  9. [LeetCode] Word Break II 拆分词句之二

    Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each ...

随机推荐

  1. 安卓第一次启动引导页使用ViewPager实现

    我们在安装某个APP的时候,基本都会有一个引导页的提示,他们可以打广告,或者介绍新功能的加入和使用说明等.一般都支持滑动并且下面有几个点,显示共有多少页和当前图片的位置,在IOS上这个实现起来比较简单 ...

  2. c#编程基础之ref、out参数

    引例: 先看这个源码,函数传递后由于传递的是副本所以真正的值并没有改变. 源码如下: using System; using System.Collections.Generic; using Sys ...

  3. Lua BehaviourTree 各节点说明

    项目说明 本行为树的代码使用Lua编写,所有的内容也建立的Lua的基础语法之上 因为公司项目需求,需要一套Lua的行为树代码,所以尝试从饥荒中抽离了行为树相关的代码.绝大多数节点行为与饥荒中相同,不过 ...

  4. C#限速下载网络文件

    代码: using System; using System.Collections.Concurrent; using System.Collections.Generic; using Syste ...

  5. Vertical Menu ver4

    以前一直使div来创建Vertical菜单,也曾有过3个版本.http://www.cnblogs.com/insus/archive/2011/10/19/2217314.html 现今Insus. ...

  6. Linux:JDK配置

    1.JDK官网下载"jdk-8u101-linux-i586.tar.gz",32位或64位. 2 命令 #创建jdk所在目录 sudo mkdir /usr/lib/jvm #找 ...

  7. simplestyle

    simplestyle-spec A simple specification for styling GeoJSON data. Versions 1.1.0 Adds properties to ...

  8. Highcharts配置

    一.基础使用 <script src="http://cdn.hcharts.cn/jquery/jquery-1.8.3.min.js"></script> ...

  9. AngularJS API

    AngularJS 全局 API 用于执行常见任务的 JavaScript 函数集合 angular.lowercase() 转换字符串为小写 angular.uppercase() 转换字符串为大写 ...

  10. CSS实现内容超过长度后以省略号显示

    样式: {width: 160px; overflow: hidden; text-overflow:ellipsis; white-space: nowrap;} 说明: white-space: ...