篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 265. Paint House II(O(n * k * k))。java相关的知识,希望对你有一定的参考价值。
public class Solution {
public int minCostII(int[][] costs) {
if (costs == null || costs.length < 1) return 0;
int n = costs.length;
int k = costs[0].length;
int prevMin = 0, prevSecMin = 0, preMinInd = -1;
for (int i = 0; i < n; i++) {
int curMin = Integer.MAX_VALUE;
int curSecMin = Integer.MAX_VALUE;
int curMinInd = -1;
for (int j = 0; j < k; j++) {
int val = costs[i][j] + (j == preMinInd ? prevSecMin : prevMin);
if (curMinInd < 0) { // initialize curMin
curMin = val;
curMinInd = j;
} else if (val < curMin) { // update curMin
curSecMin = curMin;
curMin = val;
curMinInd = j;
} else if (val < curSecMin) { // //when curMin <= val< curSecMin, update curSecMin
curSecMin = val;
}
}
prevMin = curMin;
prevSecMin = curSecMin;
preMinInd = curMinInd;
}
return prevMin;
}
}
public class Solution {
public int minCostII(int[][] costs) {
if (costs == null || costs.length == 0 || costs[0].length == 0) {
return 0;
}
for (int i = 1; i < costs.length; i++) {
for (int j = 0; j < costs[0].length; j++) {
int min = Integer.MAX_VALUE;
for (int k = 0; k < costs[0].length; k++) {
if (j == k) {
continue;
}
min = Math.min(min, costs[i - 1][k]);
}
costs[i][j] += min;
}
}
int min = Integer.MAX_VALUE;
for (int i = 0; i < costs[0].length; i++) {
min = Math.min(min, costs[costs.length - 1][i]);
}
return min;
}
}
以上是关于java 265. Paint House II(O(n * k * k))。java的主要内容,如果未能解决你的问题,请参考以下文章