1. 程式人生 > >DP動態規劃專題二 :LeetCode 265. Paint House II

DP動態規劃專題二 :LeetCode 265. Paint House II

There are a row of n houses, each house can be painted with one of the k colors. 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 k cost matrix. For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on… Find the minimum cost to paint all houses.

Note:
All costs are positive integers.

Example:

Input: [[1,5,3],[2,9,4]]
Output: 5
Explanation: Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5; 
             Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5. 

Follow up:
Could you solve it in O(nk) runtime?

思路:每次都只需要儲存前一個房子塗不同顏色的最小值即可。時間複雜度為nkk

    public int minCostII(int[][] costs) {
        if (costs.length == 0 || costs[0].length == 0) return 0;
        int house = costs.length;
        int color = costs[0].length;
        int[] dp = new int[color];
        dp = costs[0];
        for (int i = 1; i < house; i++) {
            int[] cur = new int[color];
            for (int j = 0; j < color; j++) {
                int min = Integer.MAX_VALUE;
                for (int c = 0; c < color; c++) {
                    if (c != j) {
                        min = Math.min(min, costs[i][j] + dp[c]);
                    }
                }
                cur[j] = min;
            }
            dp = cur;
        }
        int res = Integer.MAX_VALUE;
        for (int i = 0; i < dp.length; i++) {
            res = Math.min(res, dp[i]);
        }
        return res;
    }

簡化版:時間複雜度為n*k,每次只需儲存前一個房子的最小代價和塗色以及第二小代價

public int minCostII(int[][] costs) {
    if(costs == null || costs.length == 0 || costs[0].length == 0) return 0;
    
    int n = costs.length, k = costs[0].length;
    if(k == 1) return (n==1? costs[0][0] : -1);
    
    int prevMin = 0, prevMinInd = -1, prevSecMin = 0;//prevSecMin always >= prevMin
    for(int i = 0; i<n; i++) {
        int min = Integer.MAX_VALUE, minInd = -1, secMin = Integer.MAX_VALUE;
        for(int j = 0; j<k;  j++) {
            int val = costs[i][j] + (j == prevMinInd? prevSecMin : prevMin);
            if(minInd< 0) {min = val; minInd = j;}//when min isn't initialized
            else if(val < min) {//when val < min, 
                secMin = min;
                min = val;
                minInd = j;
            } else if(val < secMin) { //when min<=val< secMin
                secMin = val;
            }
        }
        prevMin = min;
        prevMinInd = minInd;
        prevSecMin = secMin;
    }
    return prevMin;
}