【EASY】Paint House

发布于: 2019-03-04 23:32
阅读: 21
评论: 0
喜欢: 0

问题

原题链接:https://leetcode.com/problems/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.

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.

Note:

  • All costs are positive integers.

Example:

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

分析过程

  • 输入:一个二维数组,N行,3 列,每一列代表用 RBG 中的一种颜色刷这个房子的 cost。
  • 输出:刷完所有房子的 cost 的最小值。
  • 思路:动态规划,使用临时空间,累计 cost。第 i 个房子用红色的 cost 等于这个房子用红色的 cost 加上第 i - 1 个房子用蓝色或绿色的累计 cost 中小的那个。
    • dp[i][0] += min(dp[i - 1][1], dp[i - 1][2])
    • dp[i][1] += min(dp[i - 1][0], dp[i - 1][2])
    • dp[i][2] += min(dp[i - 1][0], dp[i - 1][1])
    • 结束以后最后一行就是累计的 cost,找到最小的即可。

解决方法

class Solution {
public:
    int minCost(vector<vector<int>>& costs) {
        if (costs.size() == 0) {
            return 0;
        }
        // 临时空间,或者可以在原基础上修改
        // 存放涂第i个房间时,用该颜色的最小cost(累计)
        vector<vector<int>> dp = costs;
        
        for (int i = 1; i < dp.size(); ++i) {
            // 第i个房间用红色的cost等于用红色的cost加上上一个房间用蓝色或绿色中累计cost较小的那个
            dp[i][0] += min(dp[i - 1][1], dp[i - 1][2]);
            // 第i个房间用绿色的cost等于用红色的cost加上上一个房间用蓝色或红色中累计cost较小的那个
            dp[i][1] += min(dp[i - 1][0], dp[i - 1][2]);
            // 第i个房间用蓝色的cost等于用红色的cost加上上一个房间用绿色或红色中累计cost较小的那个
            dp[i][2] += min(dp[i - 1][0], dp[i - 1][1]);
        }
        
        return min(min(dp.back()[0], dp.back()[1]), dp.back()[2]);
    }
};

Thanks for reading.

All the best wishes for you! 💕