forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpaint-house-ii.cpp
80 lines (75 loc) · 3.05 KB
/
paint-house-ii.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Time: O(n * k)
// Space: O(k)
class Solution {
public:
/**
* @param costs n x k cost matrix
* @return an integer, the minimum cost to paint all houses
*/
int minCostII(vector<vector<int>>& costs) {
if (costs.empty()) {
return 0;
}
vector<vector<int>> min_cost(2, costs[0]);
const int n = costs.size();
const int k = costs[0].size();
for (int i = 1; i < n; ++i) {
int smallest = numeric_limits<int>::max(),
second_smallest = numeric_limits<int>::max();
for (int j = 0; j < k; ++j) {
if (min_cost[(i - 1) % 2][j] < smallest) {
second_smallest = smallest;
smallest = min_cost[(i - 1) % 2][j];
} else if (min_cost[(i - 1) % 2][j] < second_smallest) {
second_smallest = min_cost[(i - 1) % 2][j];
}
}
for (int j = 0; j < k; ++j) {
const int min_j = (min_cost[(i - 1) % 2][j] != smallest) ?
smallest : second_smallest;
min_cost[i % 2][j] = costs[i][j] + min_j;
}
}
return *min_element(min_cost[(n - 1) % 2].cbegin(),
min_cost[(n - 1) % 2].cend());
}
};
// Time: O(n * k)
// Space: O(k)
class Solution2 {
public:
/**
* @param costs n x k cost matrix
* @return an integer, the minimum cost to paint all houses
*/
int minCostII(vector<vector<int>>& costs) {
if (costs.empty()) {
return 0;
}
auto combine = [](const vector<int>& tmp, const vector<int>& house) {
const int smallest = *min_element(tmp.cbegin(),
tmp.cend());
const int i =
distance(tmp.begin(), find(tmp.cbegin(),
tmp.cend(),
smallest));
vector<int> tmp2(tmp);
tmp2.erase(tmp2.begin() + i);
const int second_smallest =
*min_element(tmp2.cbegin(),
tmp2.cend());
vector<int> min_cost(tmp.size(), smallest);
min_cost[i] = second_smallest;
transform(min_cost.cbegin(),
min_cost.cend(),
house.cbegin(),
min_cost.begin(),
std::plus<int>());
return min_cost;
};
vector<int> min_cost =
accumulate(costs.cbegin(), costs.cend(),
vector<int>(costs[0].size(), 0), combine);
return *min_element(min_cost.cbegin(), min_cost.cend());
}
};