55. Jump Game
題目描述:
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4]
, return true
.
A = [3,2,1,0,4]
, return false
.
難度:medium
題目中數組值表示可以jump的最大範圍,從第一個位置開始,能否jump到能到達最後一個位置。
解題思路:
可用貪心算法求本題。
用一個數 reach 表示能到達的最遠的範圍,在第一個位置規定的reach範圍一步步走下去,如果發現在 reach 範圍之內某處能達到的範圍大於 reach,
那麼我們就用更大的範圍來替換掉原先的 reach,這樣一個局部的最優貪心策略,在全局看來也是最優的,因爲 局部能夠到達的最大範圍也是全局能夠到達的最大範圍。
class Solution {
public:
bool canJump(vector<int>& nums) {
int reach = nums[0];
for (int i = 1; i < nums.size() && i <= reach; i++) {
reach = max(reach, nums[i] + i);
}
return reach >= nums.size() - 1;
}
};