方法1: 和道题和256题基本一模一样,只是颜色的数量不是固定的了。所以256的方法基本都是用于这道题目。方法1是dp,时间复杂n*k^2,n为房子数,k为颜色数,时间复杂1。这个做法会改变原数组。
class Solution {
public int minCostII(int[][] costs) {
if(costs.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(k == j) continue;
min = Math.min(min, costs[i - 1][k]);
}
costs[i][j] = costs[i][j] + min;
}
}
int res = Integer.MAX_VALUE;
for(int i = 0; i < costs[0].length; i++){
res = Math.min(res, costs[costs.length - 1][i]);
}
return res;
}
}
方法2: 1D dp。时间复杂n*k^2,空间复杂k。这个方法不会改变原数组,这个方法也是保留原数组的最好的算法。详细解释直接看lc官方解答3.
class Solution {
public int minCostII(int[][] costs) {
if(costs.length == 0) return 0;
int k = costs[0].length;
int n = costs.length;
int[] prev = costs[0];
for(int i = 1; i < n; i++){
int[] curr = new int[k];
for(int j = 0; j < k; j++){
int min = Integer.MAX_VALUE;
for(int m = 0; m < k; m++){
if(m == j) continue;
min = Math.min(min, prev[m]);
}
curr[j] = costs[i][j] + min;
}
prev = curr;
}
int res = Integer.MAX_VALUE;
for(int num : prev){
res = Math.min(res, num);
}
return res;
}
}
方法3: dp,modify original array,时间复杂nk,空间复杂1。也很简单,详细解释直接看lc官方解答4.
class Solution {
public int minCostII(int[][] costs) {
if(costs.length == 0) return 0;
int k = costs[0].length;
int n = costs.length;
for(int i = 1; i < n; i++){
int min = -1; int sec = -1;
for(int j = 0; j < k; j++){
int cost = costs[i - 1][j];
if(min == -1 || cost < costs[i - 1][min]){
sec = min;
min = j;
}else if(sec == -1 || cost < costs[i - 1][sec]){
sec = j;
}
}
for(int j = 0; j < k; j++){
if(j == min){
costs[i][j] += costs[i - 1][sec];
}else{
costs[i][j] += costs[i - 1][min];
}
}
}
int res = Integer.MAX_VALUE;
for(int num : costs[n - 1]){
res = Math.min(res, num);
}
return res;
}
}
总结:
- 无