您的位置:首页 > 编程语言 > C语言/C++

Jump Game II

2016-07-17 13:27 477 查看
题目描述:

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.

Your goal is to reach the last index in the minimum number of jumps.

For example:

Given array A = 
[2,3,1,1,4]


The minimum number of jumps to reach the last index is 
2
. (Jump 
1
 step
from index 0 to 1, then 
3
 steps to the last index.)

Note:

You can assume that you can always reach the last index.
解题思路:
使用贪心法,假设当前位于数组的index i,那么下一跳选择的步数j需要满足:max(j+nums[i+j]) 其中j>=1 且j<=nums[i]

AC代码如下:

class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size();
if (n <= 1) return 0;
int idx = 0;
int ans = 0;
while (idx < n){
if (idx == n - 1) return ans;
++ans;
if (idx + nums[idx] >= n - 1) return ans;
int step = nums[idx];
int local_max = 0;
int select_step = 0;
for (int j = 1; j <= step; ++j){
if (local_max < j + nums[idx + j]){
local_max = j + nums[idx + j];
select_step = j;
}
}
idx += select_step;
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode Jump Game II C++