码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode256- Paint House- medium

时间:2017-11-16 11:42:59      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:其他   ted   mat   note   返回值   cas   cos   each   就是   

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]));
    }
}

 

 

leetcode256- Paint House- medium

标签:其他   ted   mat   note   返回值   cas   cos   each   就是   

原文地址:http://www.cnblogs.com/jasminemzy/p/7842535.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!