Leetcode #265: 粉刷房子2

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值