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.
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.
publicclassSolution{ publicintminCost(int[][] costs){ if (costs == null || costs.length < 1) return0; int length = costs.length + 1; int[][] total = newint[length][costs[0].length]; for (int i = 0; i < 3; i++) { total[0][i] = 0; } for (int j = 1; j < length; j++) { for (int c = 0; c < 3; c++) { total[j][c] = costs[j - 1][c] + getPrevMin(total, j - 1, c); } } return Math.min(total[length - 1][2], Math.min(total[length - 1][0], total[length - 1][1])); } privateintgetPrevMin(int[][] total, int house, int color){ int min = Integer.MAX_VALUE; for (int i = 0; i < total[0].length; i++) { if (i == color && i == 0 && total[0].length - 1 == color) { return0; } elseif (i == color) { continue; } else { min = Math.min(min, total[house][i]); } } return min; } }
O(nk) time and O(1) space
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// starting from the second house/row, costs[i][0] represents the cost of painting this house red plus the previous house, etc publicclassSolution{ publicintminCost(int[][] costs){ if (costs == null || costs.length < 1){ return0; } int length = costs.length, r = 0, b = 0, g = 0; for (int i = 0; i < length; i++){ int rr = r, bb = b, gg = g; r = costs[i][0] + Math.min(bb, gg); g = costs[i][1] + Math.min(rr, bb); b = costs[i][2] + Math.min(rr, gg); } return Math.min(r, Math.min(g, b)); } }