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.
Example:
Input: [[1,5,3],[2,9,4]] Output: 5 Explanation: Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5; Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5.
题意:
一排有n套房子,每个房子可以选一种颜色(K种不同颜色)来粉刷。由于每个房子涂某种颜色的花费不同,求相邻房子不同色的粉刷最小花费。
做这个题的时候,
想起跟老妈一起去过的Santa Cruz海棠花节的时候去过的这个网红海滩。
所以这个题,对于景区想打造网红般的colorful houses来讲,还是蛮有显示意义。
思路:
维护 lastMinCost1(前一套房子的最小花费颜色色号) 和 lastMinCost2(前一套房子次小花费颜色色号)
若当前房子颜色 j 色号等于前一套房子的最小花费颜色色号lastMinCost1, 则目前为止粉刷房子的最小花费costs[i][j] = costs[i][j] + costs[i-1][lastMinCost2]
否则,若当前房子颜色 j 色号等于前一套房子的次小花费颜色色号lastMinCost2, 则目前为止粉刷房子的最小花费costs[i][j] = costs[i][j] + costs[i-1][lastMinCost1]
代码:
1 public int minCostII(int[][] costs) { 2 // sanity check 3 if (costs == null || costs.length == 0) return 0; 4 5 int n = costs.length; // n houses 6 int k = costs[0].length; // k colors 7 int minCost1 = -1; // most minimum 8 int minCost2 = -1; // second minimum 9 for (int i = 0; i < n; i++) { // scan n houses 10 11 int lastMinCost1 = minCost1; // 之前最小花费的颜色色号,先存下来 12 int lastMinCost2 = minCost2; // 之前次小花费的颜色色号,先存下来 13 14 minCost1 = -1; 15 minCost2 = -1; 16 17 // scan k colors 18 for (int j = 0; j < k; j++) { 19 if (j != lastMinCost1) { // 若当前颜色的色号不等于最小花费的颜色色号,就加上最小的开销 20 costs[i][j] += lastMinCost1 < 0 ? 0 : costs[i - 1][lastMinCost1]; 21 } else { // 若当前颜色的色号等于最小花费的颜色色号,就加上次小的开销 22 costs[i][j] += lastMinCost2 < 0 ? 0 : costs[i - 1][lastMinCost2]; 23 } 24 //更新当前最小和次小开销 25 if (minCost1 < 0 || costs[i][j] < costs[i][minCost1]) { 26 minCost2 = minCost1; 27 minCost1 = j; 28 } else if (minCost2 < 0 || costs[i][j] < costs[i][minCost2]) { 29 minCost2 = j; 30 } 31 } 32 } 33 return costs[n - 1][minCost1]; 34 }