leetcode256. whitewashed house

If there is a row of houses, a total of n, each house can be painted as a red, blue or green in three colors, all you need to paint the house and two adjacent houses it not be the same color.

Of course, because of the different color of paint on the market in different prices, so the house painted a different color it costs is different. Each house painted in different colors is spend a matrix of nx 3 represented.

For example, Costs [0] [0] represents the zeroth house painted red cost spent; costs [1] [2] No. 1 represents painted green house cost, and so on. Please work out the least cost to the cost of the house all that done.

note:

All it takes are positive integers.

Example:

Input: [[17,2,17], [16,16,5], [14,3,19]]
Output: 10
Explanation: 0 to paint the house blue, green painted house No. 1, No. 2 house painted blue.
     Minimum cost: 2 + 5 + 3 = 10.

Thinking: dp [i] [0,1,2] respectively represent the i-th lattice optimal solution must be red, blue, green brush. The dp [i] [0] of the front grid may be a blue or green, i.e. dp [i-1] [1 and dp [i-1] [2] In both cases, taking the optimal solution plus cost [ i] [0] to. Another two similar.

dp [i] and only dp [i-1] are, therefore it can be recorded by several variables.

class Solution {
    public int minCost(int[][] costs) {
        if(costs == null || costs.length == 0) return 0;
        int r_cost = costs[0][0];
        int b_cost = costs[0][1];
        int g_cost = costs[0][2];
        for(int i = 1; i < costs.length; i++){
            int r_tmp = r_cost;
            int b_tmp = b_cost;
            int g_tmp = g_cost;
            r_cost = costs[i][0] + Math.min(b_tmp, g_tmp);
            b_cost = costs[i][1] + Math.min(r_tmp, g_tmp);
            g_cost = costs[i][2] + Math.min(r_tmp, b_tmp);
        }
        return  Math.min(Math.min(r_cost, b_cost),g_cost);
    }
}

 

Published 552 original articles · won praise 10000 + · views 1.32 million +

Guess you like

Origin blog.csdn.net/hebtu666/article/details/104309849