400题,用时103天,平均3.88题/天,预计154天,也就是5个月后完成目标
1784. 检查二进制字符串字段
代码实现(模拟)
class Solution {
public:
bool checkOnesSegment(string s) {
int pos = 1;
while (pos != s.size() && s[pos] == '1') pos++;
if (pos == s.size()) return true;
while (pos != s.size() && s[pos] == '0') pos++;
if (pos == s.size()) return true;
return false;
}
};
1911. 最大子序列交替和
代码实现(dp)
class Solution {
public:
long long maxAlternatingSum(vector<int>& nums) {
long long odd = 0, even = nums[0];
for (int i = 1; i < nums.size(); i++) {
tie(odd, even) = tuple{max(even - nums[i], odd), max(odd + nums[i], even)};
}
return even;
}
};
983. 最低票价
代码实现(DFS)
class Solution {
unordered_map<int, int> mp;
int helper(vector<int> days, vector<int>& costs) {
if (days.empty()) return 0;
int answer = INT_MAX;
int curDay = days[0];
if (mp.count(curDay)) return mp[curDay];
auto it = days.begin();
it = days.erase(it);
answer = min(helper(days, costs) + costs[0], answer);
while (it != days.end() && *it < curDay + 7) it = days.erase(it);
answer = min(helper(days, costs) + costs[1], answer);
while (it != days.end() && *it < curDay + 30) it = days.erase(it);
answer = min(helper(days, costs) + costs[2], answer);
mp[curDay] = answer;
return answer;
}
public:
int mincostTickets(vector<int>& days, vector<int>& costs) {
return helper(days, costs);
}
};
787. K 站中转内最便宜的航班
代码实现(Bellman-Fold)
class Solution {
public:
int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int k) {
vector<vector<int>> dp(k + 2, vector<int>(n, INT_MAX / 2));
dp[0][src] = 0;
int res = INT_MAX / 2;
for (int t = 1; t <= k + 1; t++) {
for (auto& flight : flights) {
int i = flight[0];
int j = flight[1];
int dis = flight[2];
dp[t][j] = min(dp[t][j], dp[t-1][i] + dis);
if (j == dst) res = min(res, dp[t][j]);
}
}
return res == INT_MAX / 2 ? -1 : res;
}
};