Paint House II

67 篇文章 0 订阅
25 篇文章 0 订阅

参考:点击打开链接

第一层for是对所有房子的遍历,第二层则是对某一个房子所有颜色的遍历。所以如果,第二个房子看到此时颜色与第一个房子的颜色相同(最小的cost),那就选择另一颜色(次小的)。每个房子都要找到自身和上一个房子最小的cost和次小的cost。

理解:

if (prevIdx == k) {
                    costs[i][k] = costs[i][k] + prevSec;
                } else {
                    costs[i][k] = costs[i][k] + prevMin;
                }

public class Solution {
    public int minCostII(int[][] costs) {
        if (costs == null) {
            throw new IllegalArgumentException("haha");
        }
        if (costs.length == 0 || costs[0].length == 0) {
            return 0;
        }
        int prevMin = 0, prevSec = 0, prevIdx = -1;
        for (int i = 0; i < costs.length; i++) {
            int curMin = Integer.MAX_VALUE, curSec = Integer.MAX_VALUE, curIdx = -1;
            for (int k = 0; k < costs[0].length; k++) {
                if (prevIdx == k) {
                    costs[i][k] = costs[i][k] + prevSec;
                } else {
                    costs[i][k] = costs[i][k] + prevMin;
                }
                if (costs[i][k] < curMin) {
                    curSec = curMin;
                    curMin = costs[i][k];
                    curIdx = k;
                } else if (costs[i][k] < curSec) {
                    curSec = costs[i][k];
                }
            }
            prevMin = curMin;
            prevSec = curSec;
            prevIdx = curIdx;
        }
        return prevMin;
    }
}




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值