• leetcode256- Paint House- medium


    There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.

    The cost of painting each house with a certain color is represented by a n x 3 cost matrix. For example, costs[0][0] is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1 with color green, and so on... Find the minimum cost to paint all houses.

    Note:
    All costs are positive integers.

    DP。数组定义是:dp[i][j]表示刷到第i+1房子用颜色j的最小花费

    递推公式是:dp[i][j] = dp[i][j] + min(dp[i - 1][(j + 1) % 3], dp[i - 1][(j + 2) % 3]); 也就是每一个房子 i 刷 j 颜色的最小花费是,当前刷的花费 + 前一个房子刷其他颜色的花费里面最小的

    返回值是:dp最后一行所有列里的最小值。

    class Solution {
        public int minCost(int[][] costs) {
            
            // corner case
            if (costs == null || costs.length == 0 || costs[0].length == 0) {
                return 0;
            }
            
            // general case
            int[][] dp = new int[costs.length][costs[0].length];
            for (int j = 0; j < costs[0].length; j++) {
                dp[0][j] = costs[0][j];
            }
            
            for (int i = 1; i < costs.length; i++) {
                for (int j = 0; j < costs[0].length; j++) {
                    dp[i][j] = costs[i][j] + Math.min(dp[i - 1][(j + 1) % 3], dp[i - 1][(j + 2) % 3]);
                }
            }
            
            return Math.min(dp[dp.length - 1][0], Math.min(dp[dp.length - 1][1], dp[dp.length - 1][2]));
        }
    }
     
  • 相关阅读:
    IDEA上传项目至git
    MyBatis 三种批量插入方式的对比 !
    华为 Java 编程军规 !
    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    mysql数据库表的查询操作-总结
    idea返回git上历史版本
    JSONObject json对象-JSONArray json数组
    exception in thread "main" com.alibaba.fastjson.JSONException: exepct '[', but
    第三课
    第二课
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7842535.html
Copyright © 2020-2023  润新知