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;
}
}
这篇博客主要介绍了LeetCode难题#265,该问题与#256类似,都需要用动态规划解决。关键在于优化时间复杂度到O(K*N),避免使用for循环寻找前一排最小值,而是采用Arrays.sort()方法,其时间复杂度降低到O(logN)。博主通过比较找到的最小值与其上一排的值,确定上一排的最小值是否保持不变。

1383

被折叠的 条评论
为什么被折叠?



