跳转至

256. Paint House

Leetcode Dynamic Programming

There 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 \times 3 cost matrix. For example, costs[0][0] is the cost of painting house 0 with color red; costs[1][2] 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.

Example

Given costs = [[14,2,11],[11,14,5],[14,3,10]] return 10
house 0 is blue, house 1 is green, house 2 is blue, 2 + 5 + 3 = 10

分析

这道题目LeetCode要收费的,相应的LintCode链接

题目要求给一排房子刷漆(红绿蓝三种颜色),相邻房子的油漆颜色不能相同,而且每个房子的每种颜色的价格都是不一样的。最后让我们求给所有房子刷漆的最小费用。这道题目利用的是动态规划,需要维护一个二维的数组dp,其中dp[i][j]表示从第0套房子刷到第i套房子,其中第i套房子用颜色j的最小花费,递推式为:

dp[i][j] = dp[i][j] + min(dp[i - 1][(j + 1) % 3], dp[i - 1][(j + 2) % 3])

主要思想为第i房子有三种颜色可以刷,但如果当前房子刷了任意一种颜色,那么前一个房子i - 1肯定只能刷其他两种颜色((j + 1) % 3, (j + 2) % 3)。所以刷到当前房子用某种颜色的最小花费等于当前房子刷颜色的钱,加上刷到前一个房子用不同颜色的最小花费。

public int minCost(int[][] costs) {
    if (costs == null || costs.length == 0) return 0;
    int[][] dp = costs.clone();
    for (int i = 1; i < dp.length; ++i)
        for (int j = 0; j < 3; ++j)
            dp[i][j] += Math.min(dp[i - 1][(j + 1) % 3], dp[i - 1][(j + 2) % 3]);

    Arrays.sort(dp[dp.length - 1]);
    return dp[dp.length - 1][0];    
}