515. Paint House
There are a row of n
houses, each house can be painted with one of the three colors: red, blue or green. 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, and you need to cost the least. Return the minimum cost.
The cost of painting each house with a certain color is represented by a n
x 3
cost matrix. For example, costs[0][0]
is the cost of painting house 0
with color red; costs[1][2]
is the cost of painting house 1
with color green, and so on... Find the minimum cost to paint all houses.
Example
Example 1:
Input: [[14,2,11],[11,14,5],[14,3,10]]
Output: 10
Explanation: Paint house 0 into blue, paint house 1 into green, paint house 2 into blue. Minimum cost: 2 + 5 + 3 = 10.
Example 2:
Input: [[1,2,3],[1,4,6]]
Output: 3
Notice
All costs are positive integers.
Input test data (one parameter per line)How to understand a testcase?
解法1:坐标型DP
设定状态: fi 表示第i所房屋涂色为j时, 前i所房屋的最小花费
状态转移方程: fi = min{fi-1} +costsi (k != j)
答案: min{fn-1} i = 0, 1, 2
class Solution {
public:
/**
* @param costs: n x 3 cost matrix
* @return: An integer, the minimum cost to paint all houses
*/
int minCost(vector<vector<int>> &costs) {
int num_house = costs.size();
if (num_house == 0) return 0;
//dp[i][j] - min cost of up to house i, choose color j
vector<vector<int>> dp(num_house, vector<int>(3, 1000000));
for (int i = 0; i < 3; ++i) {
dp[0][i] = costs[0][i];
}
for (int i = 1; i < num_house; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 3; ++k) {
if (k != j) {
dp[i][j] = min(dp[i][j], dp[i - 1][k] + costs[i][j]);
//注意,写成 dp[i][j] = min(dp[i - 1][j], dp[i - 1][k] + costs[i][j]); 就错了,跟01背包不一样。
}
}
}
}
return min(dp[num_house - 1][0], min(dp[num_house - 1][1], dp[num_house - 1][2]));
}
};
解法2:类似解法1,加上滚动数组优化。