学渣带你刷Leetcode0045跳跃游戏 II

题目描述

给定一个非负整数数组,你最初位于数组的第一个位置。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

你的目标是使用最少的跳跃次数到达数组的最后一个位置。

示例:

输入: [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
     从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
说明:

假设你总是可以到达数组的最后一个位置。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jump-game-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

白话题目:
 

算法:

 

详细解释关注 B站  【C语言全代码】学渣带你刷Leetcode 不走丢 https://www.bilibili.com/video/BV1C7411y7gB

C语言完全代码

int jump(int* nums, int numsSize){
    if (nums == NULL || numsSize == 0) return 0;
    int *dest = malloc(numsSize * sizeof(int));
    memset(dest, -1, numsSize * sizeof(int));
    dest[0] = 0;
    int ret;
    for (int i = 0; i < numsSize; ++i) {
        if (dest[i] == -1) continue;
        for (int j = i + nums[i] < numsSize - 1 ? i + nums[i] : numsSize - 1; j > i; --j) {
            if (dest[j] == -1) {
                dest[j] = dest[i] + 1;
            } else if (dest[j] <= dest[i] + 1) { // 已经是最优解,前面的都是最优解
                break;
            } else { // 不是最优解,需要更新
                dest[j] = dest[i] + 1;
            }
            if (j == numsSize - 1) goto FINSH;
        }
    }
FINSH:
    ret = dest[numsSize - 1];
    free(dest);
    return ret;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章