[LeetCode] Paint House

简介: Problem Description: There are a row of n houses, each house can be painted with one of the three colors: red, blue or green.

Problem Description:

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.


An interesting DP problem. This link posts a nice solution which gives costs[i][j] a new meaning and modify it directly and so save the usage of additional spaces.

Well, personally I would like to keep costs unmodified. I rewrite the code in C++, a little verbose than the one in the above link:-)

 1 class Solution {
 2 public:
 3     int minCost(vector<vector<int>>& costs) {
 4         if (costs.empty()) return 0;
 5         int n = costs.size(), r = 0, g = 0, b = 0;
 6         for (int i = 0; i < n; i++) {
 7             int rr = r, bb = b, gg = g; 
 8             r = costs[i][0] + min(bb, gg);
 9             b = costs[i][1] + min(rr, gg);
10             g = costs[i][2] + min(rr, bb);
11         }
12         return min(r, min(b, g));
13     } 
14 };

r/b/g in the i-th loop means the minimum costs to paint the i-th house in red/blue/green respectively plus painting the previous houses. The time and space complexities are still ofO(n) and O(1).

目录
相关文章
|
6月前
|
安全
Leetcode 198. House Robber
一句话理解题意,有个偷马贼晚上要偷尽可能值钱的马,但连续两头马被偷会触发报警,问他如何在不触发报警(不偷连续的两匹马)的情况下偷到总价值最高马,返回最高总价值。
32 3
LeetCode 337. House Robber III
在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。 除了“根”之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。 计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。
41 0
LeetCode 337. House Robber III
|
安全
LeetCode 213. House Robber II
你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都围成一圈,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。
56 0
LeetCode 213. House Robber II
【LeetCode】House Robber III(337)
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automaticall
81 0

热门文章

最新文章