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

265. Paint House II

时间:2016-06-25 09:41:05      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:

      /*
       * 265. Paint House II
       * 2016-6-24 by Mingyang
       * This is a classic back pack problem. 
       * -- Define dp[n][k], where dp[i][j] means for house i with color j the minimum cost. 
       * -- Initial value: dp[0][j] = costs[0][j]. For others, dp[i][j] = Integer.MAX_VALUE;, i >= 1
       * -- Transit function: dp[i][j] = Math.min(dp[i][j], dp[i - 1][k] + cost[i][j]), where k != j.
       * -- Final state: Min(dp[n - 1][k]).
       */
      public int minCostII(int[][] costs) {
            if (costs == null || costs.length == 0) {
                return 0;
            }         
            int n = costs.length;
            int k = costs[0].length;             
            // dp[i][j] means the min cost painting for house i, with color j
            int[][] dp = new int[n][k];         
            // Initialization
            for (int i = 0; i < k; i++) {
                dp[0][i] = costs[0][i];
            }             
            for (int i = 1; i < n; i++) {
                for (int j = 0; j < k; j++) {
                    dp[i][j] = Integer.MAX_VALUE;
                    for (int m = 0; m < k; m++) {
                        if (m != j) {
                            dp[i][j] = Math.min(dp[i - 1][m] + costs[i][j], dp[i][j]);
                        }
                    }
                }
            }             
            // Final state
            int minCost = Integer.MAX_VALUE;
            for (int i = 0; i < k; i++) {
                minCost = Math.min(minCost, dp[n - 1][i]);
            }         
            return minCost;
        }

 

265. Paint House II

标签:

原文地址:http://www.cnblogs.com/zmyvszk/p/5615811.html

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