剑指 Offer II 091. 粉刷房子

本文介绍了如何使用Java实现一个解决方案,针对给定的三维成本矩阵,通过暴力匹配和模拟优化,寻找最小成本配对。重点讨论了minCost方法,包括暴力匹配的改进版和模拟求解策略。

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



import java.util.Arrays;

/**
 * @author xnl
 * @Description:
 * @date: 2022/6/25   22:43
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] costs = {{17,2,17},{16,16,5},{14,3,19}};
        solution.minCost(costs);
        System.out.println(solution.ans);
    }

    /**
     *  暴力匹配,不行,有问题
     *
     * @param costs
     * @return
     */
    int ans = 0;
    public int minCost2(int[][] costs) {
        if (costs.length == 0 || costs[0].length == 0){
            return 0;
        }
        int index = getFirstMinValue(costs[0]);
        for (int i = 1; i < costs.length; i++){
            index = getIndex(costs[i], index);
        }
        return ans;
    }

    private int getFirstMinValue(int[] arr){
        int asInt = Arrays.stream(arr).min().getAsInt();
        ans += asInt;
        int res = 0;
        for (int i = 0; i < arr.length; i++){
            if (arr[i] == asInt){
               res = i;
               break;
            }
        }
        return res;
    }

    private int getIndex(int[] arr, int index){
        int temp = 0;
        if (index == 0){
            temp = arr[1] > arr[2] ? 2 : 1;
        }
        if (index == 1){
            temp = arr[0] > arr[2] ? 2 : 0;
        }
        if (index == 2){
            temp = arr[0] > arr[1] ? 1 : 0;
        }
        ans += arr[temp];
        return temp;
    }

    /**
     * 暴力匹配,不行,有问题,hhh,使用模拟
     * @param costs
     * @return
     */
    public int minCost(int[][] costs) {
        int red = 0, green = 0, blue = 0;
        for (int[] cost : costs) {
            int r = Math.min(blue, green) + cost[0];
            int g = Math.min(blue, red) + cost[1];
            int b = Math.min(red, green) + cost[2];
            red = r;
            blue = b;
            green = g;
        }
        return Math.min(red, Math.max(green, blue));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值