zoukankan      html  css  js  c++  java
  • 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]));
        }
    }
     
  • 相关阅读:
    JavaScript 正则表达式
    android源代码提示文本框还能输入多少个字符
    js实现鼠标点击input框后里面的内容就消失代码
    使用prompt输入一句英文句子和排序方式(升/降),将所有单词按排序方式排序后在网页上输出
    Javascript输出表格
    flutter 按键监听
    3.声明
    2.基础类型
    1.安装TypeScrpit
    苹果app证书
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7842535.html
Copyright © 2011-2022 走看看