problem
solution
dp 維護的是剩餘跳力,剩餘跳力是前一個位置的剩餘跳力 -1dp[i-1]-1的
,或是前一個位置的最大跳力-1 nums[i-1]-1
取最大。如果當前剩餘跳力等於零,代表停在於此,小於零代表跳不到這裏。
option 1
1 | class Solution { |
option 2 reduce dp
1 | class Solution { |
- greedy
1
2
3
4
5
6
7
8
9
10
11
12
13class Solution {
public:
bool canJump(vector<int>& nums) {
int n =nums.size();
int canReach = 0;
for(int i=0;i<n-1;++i){
if(canReach<i) return false;
canReach = max(canReach, i+nums[i]);
}
return true;
}
};analysis
- option 1
- time complexity
O(n)
- space complexity
O(n)
- time complexity
- option 2
- time complexity
O(n)
- space complexity
O(1)
- time complexity