# 《leetCode》：Jump Game II

280人阅读 评论(0)

## 题目

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.)

## 思路

The ideas is simple ,using some greedy tactics.

We generally maintain a start position to indicate the current position,and there are only 2 main steps for solving the problem.

step(1): When you are at position start, you can go to positon start + 1 to start + nums[start] if nums[start] > 0,
and now you can know whether you can go to the end by judging nums[start] >= nums.size()-1.
If so, go to step(3). If not, go to step(2).

step(2): From start + 1 to start + nums[start], in these nums[start] positions,pick one to be the next start position.
And the rule for picking is simple:

You pick a position start + i, from which you can move forward the longest distance,
which means i + nums[start + i] >= j + nums[start + j] for any 1 <= j <= nums[start].

So the start position is at start + i now. Then you go to the step(1).

step(3): Return the answer.

int count;
void minJump(int *nums,int numsSize,int start){
if(nums==NULL||numsSize<1){
return 0;
}
count++;
int end=start+nums[start];
if(end>=numsSize-1){
return ;
}
int max=0;
int index=0;
for(int i=start+1;i<=end;i++){//寻找在这个区间中，离目标最近的那个点
if(i+nums[i]>max){
index=i;
max=i+nums[i];
}
}
minJump(nums,numsSize,index);//起点换了

}

int jump(int* nums, int numsSize) {
if(nums==NULL||numsSize<1){
return 0;
}
if(numsSize==1){//一个元素
return 0;
}
count=0;
minJump(nums,numsSize,0);
return count;

}

1
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：643571次
• 积分：12281
• 等级：
• 排名：第1374名
• 原创：606篇
• 转载：14篇
• 译文：0篇
• 评论：111条
联系方式
有问题欢迎探讨咨询哈
qq号就不留了哈
欢迎留言
博客专栏
 Hibernate学习笔记 文章：12篇 阅读：29187
 数据结构与算法分析 文章：11篇 阅读：12328
 leetcode 文章：16篇 阅读：7135
 struts2学习笔记 文章：8篇 阅读：9090
 Python爬虫实战 文章：6篇 阅读：14916
 MySQL必知必会学习笔记 文章：22篇 阅读：23843
阅读排行
评论排行
最新评论