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.

這道題是之前那道Paint House的拓展,那道題只讓用紅綠藍三種顏色來粉刷房子,而這道題讓我們用k種顏色,這道題不能用之前那題的解法,會TLE。這題的解法的思路還是用DP,但是在找不同顏色的最小值不是遍歷所有不同顏色,而是用min1和min2來記錄之前房子的最小和第二小的花費的顏色,如果當前房子顏色和min1相同,那麼我們用min2對應的值計算,反之我們用min1對應的值,這種解法實際上也包含了求次小值的方法,感覺也是一種很棒的解題思路,參見代碼如下:

public class Solution {
    public int minCostII(int[][] costs) {
        if(costs == null || costs.length == 0 || costs[0]. length == 0){  
            return 0;  
        }  
        int min1 = 0, min2 = 0, preIndex = -1;
        for(int i=0; i<costs.length; i++){
            int m1 = Integer.MAX_VALUE, m2 = Integer.MAX_VALUE, curIndex = -1; //curIndex一定要保留,不然會在下面被沖掉
            for(int j=0; j<costs[0].length; j++){
                int cost = costs[i][j] + (j == preIndex ? min2: min1); //不保留的話這裏就被沖掉了
                if(m1 > cost){ //求第二小的元素的方法
                    m2 = m1;
                    m1 = cost;
                    curIndex = j;
                }else if(m2 > cost){
                    m2 = cost;
                }
            }
            min1 = m1; 
            min2 = m2;
            preIndex = curIndex;
        }
        return min1;
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章