参考:点击打开链接
第一层for是对所有房子的遍历,第二层则是对某一个房子所有颜色的遍历。所以如果,第二个房子看到此时颜色与第一个房子的颜色相同(最小的cost),那就选择另一颜色(次小的)。每个房子都要找到自身和上一个房子最小的cost和次小的cost。
理解:
if (prevIdx == k) {
costs[i][k] = costs[i][k] + prevSec;
} else {
costs[i][k] = costs[i][k] + prevMin;
}
public class Solution {
public int minCostII(int[][] costs) {
if (costs == null) {
throw new IllegalArgumentException("haha");
}
if (costs.length == 0 || costs[0].length == 0) {
return 0;
}
int prevMin = 0, prevSec = 0, prevIdx = -1;
for (int i = 0; i < costs.length; i++) {
int curMin = Integer.MAX_VALUE, curSec = Integer.MAX_VALUE, curIdx = -1;
for (int k = 0; k < costs[0].length; k++) {
if (prevIdx == k) {
costs[i][k] = costs[i][k] + prevSec;
} else {
costs[i][k] = costs[i][k] + prevMin;
}
if (costs[i][k] < curMin) {
curSec = curMin;
curMin = costs[i][k];
curIdx = k;
} else if (costs[i][k] < curSec) {
curSec = costs[i][k];
}
}
prevMin = curMin;
prevSec = curSec;
prevIdx = curIdx;
}
return prevMin;
}
}