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.
All costs are positive integers.
Follow up:
Could you solve it in O(nk) runtime?
Could you solve it in O(nk) runtime?
Solution 1: a DP question. Can be solved with O(k) space and O(nk) time.
public class Solution {
public int minCostII(int[][] costs) {
int n=costs.length;
if (n==0) return 0;
int k=costs[0].length;
//if (k<2) return 0;// n==1 and k==1 still works
int[] dp=new int[k];
for (int i=0; i<n; i++) {
if (i==0) {
for (int j=0; j<k; j++) dp[j]=costs[i][j];
}
else {
int m1=-1, m2=-1, v1=Integer.MAX_VALUE, v2=Integer.MAX_VALUE;
for (int j=0; j<k; j++) {
if (dp[j]<=v1) {
m2=m1;
m1=j;
v2=v1;
v1=dp[j];
}
else if (dp[j]<=v2) {
m2=j;
v2=dp[j];
}
}
for (int j=0; j<k; j++) dp[j]=costs[i][j]+((j==m1)?v2:v1);
}
}
int res=Integer.MAX_VALUE;
for (int j=0; j<k; j++) res=Math.min(res,dp[j]);
return res;
}
}
没有评论:
发表评论