LintCode 515: Paint House (坐标型DP)

515. Paint House

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, and you need to cost the least. Return the minimum cost.

The cost of painting each house with a certain color is represented by a n x 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.

Example

Example 1:

Input: [[14,2,11],[11,14,5],[14,3,10]]
Output: 10
Explanation: Paint house 0 into blue, paint house 1 into green, paint house 2 into blue. Minimum cost: 2 + 5 + 3 = 10.

Example 2:

Input: [[1,2,3],[1,4,6]]
Output: 3

Notice

All costs are positive integers.

Input test data (one parameter per line)How to understand a testcase?

 

解法1:坐标型DP

设定状态: fi 表示第i所房屋涂色为j时, 前i所房屋的最小花费

状态转移方程: fi = min{fi-1} +costsi (k != j)

边界: f0 = costs0

答案: min{fn-1} i = 0, 1, 2

class Solution {
public:
    /**
     * @param costs: n x 3 cost matrix
     * @return: An integer, the minimum cost to paint all houses
     */
    int minCost(vector<vector<int>> &costs) {
        int num_house = costs.size();
        if (num_house == 0) return 0;

        //dp[i][j] - min cost of up to house i, choose color j
        vector<vector<int>> dp(num_house, vector<int>(3, 1000000));
        
        for (int i = 0; i < 3; ++i) {
            dp[0][i] = costs[0][i];
        }

        for (int i = 1; i < num_house; ++i) {
            for (int j = 0; j < 3; ++j) {
                for (int k = 0; k < 3; ++k) {
                    if (k != j) {
                        dp[i][j] = min(dp[i][j], dp[i - 1][k] + costs[i][j]);
//注意,写成 dp[i][j] = min(dp[i - 1][j], dp[i - 1][k] + costs[i][j]); 就错了,跟01背包不一样。                              
                    }
                }
            }
        }
        
        return min(dp[num_house - 1][0], min(dp[num_house - 1][1], dp[num_house - 1][2])); 
    }
};

解法2:类似解法1,加上滚动数组优化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值