256. Paint House

303 查看

题目:
here are a row of n houses, each house can be painted with one of the three colors: red, blue or green. 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 3 cost matrix. For example, costs0 is the cost of painting house 0 with color red; costs1 is the cost of painting house 1 with color green, and so on... Find the minimum cost to paint all houses.

Note:
All costs are positive integers.

解答:
这类题还是先找临时的结果,由临时的结果最终推出最终解。比如说用f(i, j)存到i个house的时候最小的cost.但是到第i个house的时候,有三种情况:涂red, blue or green.当我涂红的时候,前面一个只能涂蓝或者绿,所以我只能加上这两种情况的最小值,作为此次计算的最小值,以此类推。

public class Solution {
    //State: f[i][j] is the minimum cost of painting i houses with color j -> (red, blue, green)
    //Function: f[i][0] = Math.min(f[i - 1][1], f[i - 1][2]) + costs[i][0]
    //          f[i][1] = Math.min(f[i - 1][0], f[i - 1][2]) + costs[i][1]
    //          f[i][2] = Math.min(f[i - 1][0], f[i - 1][1]) + costs[i][2]
    //Initialize: f[0][0] = costs[0][0], f[0][1] = costs[0][1], f[0][2] = costs[0][2];
    //Result: Math.min(f[costs.length - 1][0], f[costs.length - 1][1], f[costs.length - 1][2]);
    public int minCost(int[][] costs) {
        if (costs == null || costs.length == 0 || costs[0].length == 0) {
            return 0;
        }
        
        int house = costs.length, color = costs[0].length;
        int[][] f = new int[house][color];
        //Initialize
        f[0][0] = costs[0][0];
        f[0][1] = costs[0][1];
        f[0][2] = costs[0][2];
        //Function
        for (int i = 1; i < house; i++) {
            f[i][0] = Math.min(f[i - 1][1], f[i - 1][2]) + costs[i][0];
            f[i][1] = Math.min(f[i - 1][0], f[i - 1][2]) + costs[i][1];
            f[i][2] = Math.min(f[i - 1][0], f[i - 1][1]) + costs[i][2];
        }
        
        return Math.min(f[house - 1][0], Math.min(f[house - 1][1], f[house - 1][2]));
    }
}