-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path2742.cpp
More file actions
64 lines (53 loc) · 1.84 KB
/
Copy path2742.cpp
File metadata and controls
64 lines (53 loc) · 1.84 KB
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
// Top-down
class Solution {
static int dp[501][501];
public:
Solution() { memset(dp, 0xFF, sizeof(dp)); }
int paintWalls(const vector<int> &cost, const vector<int> &time, int crnt = 0, int total = 0) {
if (total >= cost.size()) return 0;
if (crnt == cost.size()) return 1e9;
if (dp[crnt][total] != -1) return dp[crnt][total];
const int paint = cost[crnt] + paintWalls(cost, time, crnt + 1, total + time[crnt] + 1);
const int dont = paintWalls(cost, time, crnt + 1, total);
return dp[crnt][total] = min(paint, dont);
}
};
int Solution::dp[501][501];
// Bottom-up
class Solution {
public:
int paintWalls(const vector<int> &cost, const vector<int> &time) {
static unsigned dp[501][501];
memset(dp, 0x00, sizeof(dp));
const int n = cost.size();
for (int i = 1; i <= 500; i++)
dp[n][i] = 1e9;
for (int i = n - 1; i >= 0; i--) {
for (int remain = 1; remain <= n; remain++) {
const int paint = cost[i] + dp[i + 1][max(0, remain - time[i] - 1)];
const int dont = dp[i + 1][remain];
dp[i][remain] = min(paint, dont);
}
}
return dp[0][n];
}
};
// Space optimized Bottom-up
class Solution {
public:
int paintWalls(const vector<int> &cost, const vector<int> &time) {
static unsigned dp[501], pdp[501];
const int n = cost.size();
for (int i = 1; i <= 500; i++)
pdp[i] = 1e9;
for (int i = n - 1; i >= 0; i--) {
for (int remain = 1; remain <= n; remain++) {
const int paint = cost[i] + pdp[max(0, remain - time[i] - 1)];
const int dont = pdp[remain];
dp[remain] = min(paint, dont);
}
swap(dp, pdp);
}
return pdp[n];
}
};