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

你可能感兴趣的:(dp)