Leetcode 265. Paint House II

在这里插入图片描述
方法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;
    }
}

总结:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值