关闭

《leetCode》:Jump Game II

标签: leetcode游戏贪婪算法
240人阅读 评论(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.)

题目大意:找出到达最后一个元素需要的最小的步数时多少??

思路

思路来源于leetCode中本题的讨论组。
应用贪婪算法。
有一点需要说明的是:所有测试用例必须是能够到达终点的,不允许出现不可达的这种情况:[0,1,2]

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;

}

最后AC结果如下:

1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:457664次
    • 积分:10712
    • 等级:
    • 排名:第1612名
    • 原创:600篇
    • 转载:14篇
    • 译文:0篇
    • 评论:90条
    联系方式
    有问题欢迎探讨咨询哈
    qq号就不留了哈
    欢迎留言
    博客专栏
    最新评论