F面经:painting house
There are a row of houses, each house can be painted with three colors red, blue and 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. You have to paint the houses with minimum cost. How would you do it? Note: Painting house-1 with red costs different from painting house-2 with red. The costs are different for each house and each color.
一个dp,f(i,j)表示前i个house都paint了且第i个house paint成color_j的最小cost。
1 int paint(int N, int M, int[][] cost) { 2 int[][] res = new int[N+1][M]; 3 for (int t=0; t<M; t++) { 4 res[0][t] = 0; 5 } 6 for (int i=1; i<N; i++) { 7 for (int j=0; j<M; j++) { 8 res[i][j] = Integer.MAX_VALUE; 9 } 10 } 11 for (int i=1; i<=N; i++) { 12 for (int j=0; j<M; j++) { 13 for (int k=0; k<M; k++) { 14 if (k != j) { 15 res[i][j] = Math.min(res[i][j], res[i-1][k]+cost[i-1][j]); // 16 } 17 } 18 } 19 } 20 int result = Integer.MAX_VALUE; 21 for (int t=0; t<M; t++) { 22 result = Math.min(result, res[N][t]); 23 } 24 return result; 25 }