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
|
class Solution {
public:
int ans = INT_MAX;
// check current have whether satisfy the needs
bool checkItemsEqual(vector<int>& needs, vector<int>& have) {
for (int i = 0; i < needs.size(); i++) {
if(needs[i] != have[i]) {
return false;
}
}
return true;
}
// check current add this special whether more than the needs
bool checkItemsMore(vector<int>& needs, vector<int>& have, vector<int>shoppingOffer) {
for (int i = 0; i < needs.size(); i++) {
if(have[i] + shoppingOffer[i] > needs[i]) {
return false;
}
}
return true;
}
// inc to have or dec from have
void add(vector<int>& shoppingOffer, vector<int>& have, bool inc) {
if(inc) {
for (int i = 0; i < shoppingOffer.size(); i++) {
have[i] += shoppingOffer[i];
}
} else {
for (int i = 0; i < shoppingOffer.size(); i++) {
have[i] -= shoppingOffer[i];
}
}
}
void dfs(vector<vector<int>>& special, vector<int>& needs, vector<int>& have, int idx) {
if (idx == special.size()) {
if (checkItemsEqual(needs, have)) {
ans = min(have.back(), ans);
}
return;
}
// don't choose this idx
dfs(special, needs, have, idx+1);
// choose this idx
if (checkItemsMore(needs, have, special[idx])) {
add(special[idx], have, true);
dfs(special, needs, have, idx);
add(special[idx], have, false);
}
}
int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) {
int n = price.size();
// view a item as a shopping offers.
for (int i = 0; i < n; i++) {
vector<int> t(n + 1, 0);
t[i] = 1;
t[n] = price[i];
// add this to shopping offers
special.push_back(t);
}
// current items and prices
vector<int> have(n + 1, 0);
dfs(special, needs, have, 0);
return ans;
}
};
|