HARD难度,思路和256几乎完全相同,先初始化第一排然后用动态转移方程,但是难点在于题目中要求Time complexity为O(K*N),如果用for循环来寻找前一排的最小值花费过大,我使用的是Arrays.sort(),时间复杂度为O(logN)。找到最小值以后和当前值的上一排做对比,来确定上一排的最小值是不是自己。
class Solution {
public int minCostII(int[][] costs) {
int n = costs.length;
if(n == 0) return 0;
int k = costs[0].length;
int[][] total_costs = new int[n][k];
int[] temp = new int[k];
for(int i=0; i<k; i++){
total_costs[0][i] = costs[0][i];
}
if(n > 1){
for(int i=1; i<n; i++){
for(int j=0; j<k; j++){
temp[j] = total_costs[i-1][j];
}
Arrays.sort(temp);
for(int j=0; j<k; j++){
if(total_costs[i-1][j]==temp[0]){
total_costs[i][j] = costs[i][j] + temp[1];
}else{
total_costs[i][j] = costs[i][j] + temp[0];
}
}
}
}
int min = Integer.MAX_VALUE;
for(int i=0; i<k; i++){
min = Math.min(min, total_costs[n-1][i]);
}
return min;
}
}