[LeetCode] Paint House I & II

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.

 1 class Solution {
 2 public:
 3     int minCost(vector<vector<int>>& costs) {
 4         if (costs.empty()) return 0;
 5         for (int i = 1; i < costs.size(); ++i) {
 6             for (int j = 0; j < 3; ++j) {
 7                 costs[i][j] += min(costs[i-1][(j+1)%3], costs[i-1][(j+2)%3]);
 8             }
 9         }
10         return min(costs.back()[0], min(costs.back()[1], costs.back()[2]));
11     }
12 };

 

 

Paint House II

There are a row of n houses, each house can be painted with one of the k colors. 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 k cost matrix. For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2]is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses.

Note:
All costs are positive integers.

Follow up:
Could you solve it in O(nk) runtime?

 1 class Solution {
 2 public:
 3     int minCostII(vector<vector<int>>& costs) {
 4         if (costs.empty() || costs[0].empty()) return 0;
 5         int n = costs.size(), k = costs[0].size();
 6         vector<int> min1(k), min2(k);
 7         for (int i = 1; i < costs.size(); ++i) {
 8             min1[0] = INT_MAX;
 9             for (int j = 1; j < k; ++j) {
10                 min1[j] = min(min1[j-1], costs[i-1][j-1]);
11             }
12             min2[k-1] = INT_MAX;
13             for (int j = k - 2; j >= 0; --j) {
14                 min2[j] = min(min2[j+1], costs[i-1][j+1]);
15             }
16             for (int j = 0; j < k; ++j) {
17                 costs[i][j] += min(min1[j], min2[j]);
18             }
19         }
20         int res = INT_MAX;
21         for (auto c : costs.back()) {
22             res = min(res, c);
23         }
24         return res;
25     }
26 };

快速找到数组中去掉某个元素的最小值方法:定义两个数组,min1[i]与min2[i]分别记录从左向右到第i位与从右向左到第i位的区间最小值,那么去掉第i位的最小值就是min(min1[i], min2[i])。

posted @ 2015-09-06 10:56  Eason Liu  阅读(2186)  评论(0编辑  收藏  举报