Paint House(房屋染色)

http://www.lintcode.com/en/problem/paint-house/?rand=true

public class Solution {
    /**
     * @param costs n x 3 cost matrix
     * @return an integer, the minimum cost to paint all houses
     */
    public int minCost(int[][] costs) {
        // Write your code here
        int[][] dp = new int[costs.length + 1][3];
//        dp[i][j]表示第i个房子,刷第j种颜色的最小花费
        for (int i = 1; i < dp.length; i++) {
            for (int j = 0; j < 3; j++) {
                dp[i][j] = Integer.MAX_VALUE;
//                先默认最大值
                for (int k = 0; k < 3; k++) {
//                    k在三种颜色中循环,不能和j的颜色相同,注意i是比原来大1
                    if (k != j) {
//                        不相同时就是原来的最小花费加上自己当次的花费
                        dp[i][j] = Math.min(dp[i - 1][k] + costs[i - 1][j], dp[i][j]);
                    }
                }
            }
        }
        return Math.min(Math.min(dp[costs.length][0], dp[costs.length][1]), dp[costs.length][2]);
    }
}

你可能感兴趣的:(Paint House(房屋染色))