LintCode刷题笔记-- PaintHouse 1&2

标签:

动态规划

题目描述:

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 0costs[1][2] is the cost of painting house 1with color 2, and so on... Find the minimum cost to paint all houses.

Example

Given n = 3, k = 3, costs =[[14,2,11],[11,14,5],[14,3,10]] return 10

house 0 is color 2, house 1 is color 3, house 2 is color 2,2 + 5 + 3 = 10

解题思路:

这两题较比之前的题目来讲要简单很多,子状态非常明显,转移方程非常容易得到

1.对于每一个房子,都k种设计方案。第n间房子的每种颜色的方案依赖于,第n-1间房子的其他颜色的最省钱方案。

2.初始状态,只有一间房子的时候,颜色价格方案是已知的。

参考代码:

public int minCostII(int[][] costs) {
        // Write your code here
        if(costs.length == 0||costs[0].length == 0) return 0;
        int n = costs.length;
        int k = costs[0].length;
        
        
        int[][] dp = new int[n][k];
        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++){
                int tmp_min = Integer.MAX_VALUE;
                for(int m = 0; m<k; m++){
                    if(m==j){
                        continue;
                    }else{
                        tmp_min = Math.min(tmp_min, dp[i-1][m]);
                    }
                }
                dp[i][j] = tmp_min+costs[i][j];
            }
        }
    
        int min = Integer.MAX_VALUE;
        for(int i=0; i<k; i++){
            min = Math.min(min, dp[n-1][i]);
        }
        
        return min;
    }

 

 

posted @ 2016-09-10 04:54  whaochen  阅读(168)  评论(0编辑  收藏  举报