您的位置:首页 > 大数据 > 人工智能

[LeetCode265]Paint House II

2015-11-26 02:58 453 查看
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?

Hide Company Tags Facebook
Hide Tags Dynamic Programming
Hide Similar Problems (M) Product of Array Except Self (H) Sliding Window Maximum (M) Paint House (E) Paint Fence


这题这么不简单,我当然不会。参考了大家的O(nk)方法。

dp[j]: 刷前i个房子且最后一个房子用的是j颜色的minimum cost。

min1: 刷前i个房子最后用某个颜色时最小的cost。

min2: 刷前i个房子最后用另外某个颜色时第二小的cost。

对于当前房子,如果之前的房子的minimum cost并不是min1 我们可以直接选取min1的颜色,否则选取min2的颜色。因为只要相邻两个房子颜色不一样即可。

class Solution {
public:
int minCostII(vector<vector<int>>& costs) {
if (costs.empty()) return 0;
int n = costs.size(), k = costs[0].size(), min1 = 0, min2 = 0;
vector<int> dp(k,0);
for(int i = 0; i<n; ++i){
int tmp1 = min1, tmp2 = min2;
min1 = min2 = INT_MAX;
for(int j = 0; j<k; ++j){
dp[j] = ((dp[j] == tmp1) ? tmp2 : tmp1) + costs[i][j];
if(min1 <= dp[j]) min2 = min(min2, dp[j]);
else{
min2 = min1;
min1 = dp[j];
}
}
}
return min1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode