自己解法一:
class Solution {
public:
int mincostTickets(vector<int>& days, vector<int>& costs) {
int len = days.size();
if (len == 0) {
return 0;
}
vector<int> dp(len);
dp[0] =
*min_element(costs.begin(), costs.end()); // costs[0]; // !!!!天啦
for (int i = 0; i < len - 1; i++) {
vector<int> tmp;
int k1 = -1;
int k2 = -1;
int k3 = -1;
for (int j = i; j >= 0; j--) {
if (days[i + 1] - days[j] + 1 > 1) {
k1 = j;
}
}
if (k1 >= 0) {
tmp.push_back(dp[i] + costs[0]);
} else {
tmp.push_back(costs[0]);
}
for (int j = i; j >= 0; j--) {
if (days[i + 1] - days[j] + 1 > 7) {
k2 = j;
break;
}
}
if (k2 >= 0) {
tmp.push_back(dp[k2] + costs[1]);
} else {
tmp.push_back(costs[1]);
}
for (int j = i; j >= 0; j--) {
if (days[i + 1] - days[j] + 1 > 30) {
k3 = j;
break;
}
}
if (k3 >= 0) {
tmp.push_back(dp[k3] + costs[2]);
} else {
tmp.push_back(costs[2]);
}
dp[i + 1] = *min_element(tmp.begin(), tmp.end());
cout << "i: " << i + 1 << " costs: " << dp[i + 1] << endl;
}
return dp[len - 1];
}
};
自己解法二:回溯超时
class Solution {
public:
int mincostTickets(vector<int>& days, vector<int>& costs) {
int len = days.size();
if (len == 0) {
return 0;
}
stack<vector<int>> s;
stack<pair<int, int>> path;
s.push({-1, -1, 0});
path.push({-1, -1});
vector<int> prices;
vector<vector<int>> ans;
while (s.empty() == false) {
auto p = s.top();
s.pop();
path.push({p[0], p[1]});
int l = p[0];
int r = p[1];
prices.push_back(p[2]);
if (r == len - 1) {
ans.push_back(prices);
for (auto p : prices) {
cout << p << " ";
}
cout << endl;
while (s.empty() == false && ((path.top().second + 1) != s.top().at(0))) {
path.pop();
prices.pop_back();
}
}
for (int j = r + 1; j < len; j++) {
if (days[j] - days[r + 1] + 1 >= 1) {
s.push({r + 1, j, costs[0]});
break;
}
}
for (int j = r + 1; j < len; j++) {
if (days[j] - days[r + 1] + 1 > 7) {
s.push({r + 1, j - 1, costs[1]});
break;
} else if (j == len - 1) {
s.push({r + 1, len - 1, costs[1]});
}
}
for (int j = r + 1; j < len; j++) {
if (days[j] - days[r + 1] + 1 > 30) {
s.push({r + 1, j - 1, costs[2]});
break;
} else if (j == len - 1) {
s.push({r + 1, len - 1, costs[2]});
}
}
}
int minPrice = INT_MAX;
for (auto price : ans) {
int sum = accumulate(price.begin(), price.end(), 0);
minPrice = (minPrice < sum) ? minPrice : sum;
}
return minPrice;
}
};
力友解法三:
class Solution {
public:
int mincostTickets(vector<int>& days, vector<int>& costs) {
int sz = days.size();
vector<int> dp(sz+1, 0);
dp[1] = *min_element(costs.begin(), costs.end());
int last7, last30;
for (int i = 2; i<=sz; i++) {
last7 = upper_bound(days.begin(), days.begin() + i, days[i-1] - 7) - days.begin();
last30 = upper_bound(days.begin(), days.begin() + i, days[i-1] - 30) - days.begin();
dp[i] = min(costs[0] + dp[i - 1], min(costs[1] + dp[last7], costs[2] + dp[last30]));
}
return dp[sz];
}
};