您的位置:首页 > 其它

[leetcode-45]Jump Game II(c)

2015-08-02 15:59 441 查看
问题描述:

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

分析:该题是典型的DP问题,但是如果直接用DP算法,如代码1会超时,这里面有个trick就是,当上一次通过DP已经计算到的结尾,记录下来,当继续遍历的时候就从上次遍历的结尾处开始,因为,即使重复遍历,其结果也只会大于等于前者。所以不如直接跳过。另外,最后一个节点,一点被设置就立即返回。不必再遍历了。

代码1:TLE

[code]int jump(int *nums,int numsSize){
    int i,j;
    int *steps = (int *)malloc(sizeof(int)*numsSize);

    for(i = 0;i<numsSize;i++)
        steps[i] = -1;
    steps[0] = 0;

    for(i = 0;i<numsSize;i++){
        int val = nums[i];
        for(j = i+1;j<=i+val&&j<numsSize;j++){
            if(steps[j]==-1||steps[j]>steps[i]+1)
                steps[j] = steps[i]+1;
        }
    }
    return steps[numsSize-1];
}


AC代码如下:8ms

[code]int jump(int *nums,int numsSize){
    int i,j;
    int *steps = (int *)malloc(sizeof(int)*numsSize);

    for(i = 0;i<numsSize;i++)
        steps[i] = -1;
    steps[0] = 0;

    int endIndex = 1;
    for(i = 0;i<numsSize;i++){
        int val = nums[i];
        for(j = endIndex;j<=i+val&&j<numsSize;j++){
            if(steps[j]==-1||steps[j]>steps[i]+1)
                steps[j] = steps[i]+1;
            if(j==numsSize-1)
                return steps[j];
        }
        endIndex = i+val+1;
    }
    return steps[numsSize-1];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: