Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
class Solution {
public:
bool canJump(vector<int>& nums) {
int mx = 0;
for (int i = 0; i < size(nums); ++i) {
if (i > mx) {
return false;
}
mx = max(mx, i + nums[i]);
}
return true;
}
};
dp[i]
表示到达 i
位置时还能跳的最大距离class Solution {
public:
bool canJump(vector<int>& nums) {
if (empty(nums)) {
return false;
}
if (size(nums) == 1 && nums[0] >= 0) {
return true;
}
vector<int> dp(size(nums));
dp[0] = nums[0];
if (dp[0] == 0) {
return false;
}
for (int i = 1; i < size(dp); ++i) {
dp[i] = max(dp[i - 1] - 1, nums[i - 1]);
if (dp[i] == 0) {
return false;
}
}
return true;
}
};