55. Jump Game

来源:互联网 发布:儿童绘画软件 编辑:程序博客网 时间:2024/06/16 06:10

55. Jump Game

题目描述:

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.

Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

难度:medium

题目中数组值表示可以jump的最大范围,从第一个位置开始,能否jump到能到达最后一个位置。

解题思路:

可用贪心算法求本题


用一个数 reach 表示能到达的最远的范围,在第一个位置规定的reach范围一步步走下去,如果发现在 reach 范围之内某处能达到的范围大于 reach,

那么我们就用更大的范围来替换掉原先的 reach,这样一个局部的最优贪心策略,在全局看来也是最优的,因为 局部能够到达的最大范围也是全局能够到达的最大范围。


class Solution {public:    bool canJump(vector<int>& nums) {        int reach = nums[0];        for (int i = 1; i < nums.size() && i <= reach; i++) {            reach = max(reach, nums[i] + i);        }        return reach >= nums.size() - 1;    }};






原创粉丝点击