265. Paint House II

Posted 我的名字叫周周

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了265. Paint House II相关的知识,希望对你有一定的参考价值。

      /*
       * 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的主要内容,如果未能解决你的问题,请参考以下文章

265. Paint House II

leetcode265- Paint House II- hard

LeetCode 265: Paint House II

java 265. Paint House II(O(n * k * k))。java

java 265. Paint House II(O(n * k * k))。java

java 265. Paint House II(O(n * k * k))。java