LintCode Q 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 1:Input: [[14,2,11],[11,14,5],[14,3,10]] ; Output: 10
Explanation: blue green blue, 2 + 5 + 3 = 10
Example 2:Input: [[1,2,3],[1,4,6]] ; Output: 3
Notice: All costs are positive integers.
Solution : DP
Solution 1
State Transfer Function:dp[i][0] = Math.min(dp[i-1][1], dp[i-1][2]) + costs[i][0];
dp[i][1] = Math.min(dp[i-1][0], dp[i-1][2]) + costs[i][1];
dp[i][2] = Math.min(dp[i-1][0], dp[i-1][1]) + costs[i][2];
Code:
public int minCost(int[][] costs) {
if (costs.length==0) return 0;
int n = costs.length;
int[][] dp = new int[n][3];
dp[0][0] = costs[0][0];
dp[0][1] = costs[0][1];
dp[0][2] = costs[0][2];
for (int i = 1; i < n; i++) {
dp[i][0] = Math.min(dp[i-1][1], dp[i-1][2]) + costs[i][0];
dp[i][1] = Math.min(dp[i-1][0], dp[i-1][2]) + costs[i][1];
dp[i][2] = Math.min(dp[i-1][0], dp[i-1][1]) + costs[i][2];
}
return Math.min(dp[n-1][0], Math.min(dp[n-1][1], dp[n-1][2]));
}
Solution 2: Optimizing the space complexity using sliding arrays
Code:
public int minCost(int[][] costs) {
if (costs.length==0) return 0;
int[][] dp = new int[2][3];
int old = 0, now = 0;
dp[0][0] = costs[0][0];
dp[0][1] = costs[0][1];
dp[0][2] = costs[0][2];
for (int i = 1; i < costs.length; i++) {
old = now; // old = 0 now = 1 or old = 1 now = 0
now = 1 - old;
dp[now][0] = Math.min(dp[old][1], dp[old][2]) + costs[i][0];
dp[now][1] = Math.min(dp[old][0], dp[old][2]) + costs[i][1];
dp[now][2] = Math.min(dp[old][0], dp[old][1]) + costs[i][2];
}
return Math.min(dp[now][0], Math.min(dp[now][1], dp[now][2]));
}
Sliding arrays is always used to save the space complexity.
For example:
Tradition method for solving the Fibonacci problemint f[100];
f[0] = 0;
f[1] = 1;
f[2] = 1;
for(int i = 3; i <= n; ++i)
f[i] = f[i - 1] + f[i - 2];
return f[n];
Sliding array for solving the Fibonacci problemint f[3];
f[1] = 0;
f[2] = 1;
for(int i = 2; i <= n; ++i)
{
f[0] = f[1];
f[1] = f[2];
f[2] = f[0] + f[1];
}
return f[2];