跳跃游戏: 贪心算法

贪心算法(又称贪婪算法)是指,在对问题求解时,不从整体最优上加以考虑,算法得到的是在某种意义上的局部最优解。
思路:
把求解的问题分成若干个子问题;
对每个子问题求解,得到子问题的局部最优解;
把子问题的解局部最优解合成原来求解问题的一个解。

常见的购物找零钱问题

const greedyMoney = function(n, sum){
    let arr = [];
    n.sort((a, b) => b - a);
    for (let i = 0; i < n.length; i++) {
        // 局部最优解
        while (sum >= n[i] && sum > 0) {
            arr.push(n[i]);
            sum -= n[i];
        }
    }
    return arr;
}

1、跳跃游戏

给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个位置。
示例 1:

输入: [2,3,1,1,4]
输出: true
解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。

示例 2:

输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。

题解

const canJump = function(nums) {
    let max = 0;
    for (let i = 0; i < nums.length-1; i++) {
        if (max < i) return false;
        max = Math.max(max, i + nums[i]);
    }
    return max >= nums.length-1;
};

2、跳跃游戏 II

给定一个正整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
示例 :

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

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

题解

const jump = function(nums) {
    let pos = 0, step = 0;
    while (pos < nums.length - 1) {
        step++;
        if (pos + nums[pos] >= nums.length - 1)
            break;
        else {
            // 当前pos可跳跃的最远距离
            let max = 0, begin = pos + 1, end = pos + nums[pos];
            for (let i = begin; i <= end; i++) {
                if (i + nums[i] > max) {
                    max = i + nums[i];
                    pos = i;
                }
            }
        }
    }
    return step;
};

题解优化

const jump = function(nums) {
    if (nums.length <= 1) return 0;
    let pos = 0, end = 0, step = 0;
    while (1) {
        let max = 0;
        for (let i = pos; i <= end; i++) {
            max = Math.max(max, i + nums[i]);
        }
        step++;
        pos = end + 1;
        end = max;
        if (end >= nums.length - 1) break;
    }
    return step;
};

你可能感兴趣的:(跳跃游戏: 贪心算法)