55. Jump Game

来源:互联网 发布:seo和sem哪个好点 编辑:程序博客网 时间:2024/05/17 02:31

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.

这题限制了非负元素,我一开始的思路判断就是什么情况下才蹦不到最后一个位置,那就是在0的地方卡住了,毕竟即使所有都是1,也能一步步走到最后,只有前面的步数不够大,跨不过0,到0就卡住了。所以我给出的解法是先线性扫描,遇到0停下来,判断这个0之前的这一段能否跨过0。

方法一:找到决定性条件进行判断

bool canJump(vector<int>& nums) {    int i, j, max_step = 0;    for (i = 0; i < nums.size(); i++) {        if (nums[i] == 0) {            for (j = i - 1; j >= 0 && nums[j] != 0; j--) {                max_step = max(max_step, j + nums[j]);            }            if (max_step == i && i == nums.size() - 1) return true;            if (max_step <= i) return false;        }    }    return true;}

方法二: 动态规划法

其实两种方法差不多。这种是经典的动态规划问题,不停的计算局部最优解,更新全局最优解,然后判断。

  1. 能跳到位置i的条件:i<=maxIndex。
  2. 一旦跳到i,则maxIndex = max(maxIndex, i+A[i])。
  3. 能跳到最后一个位置n-1的条件是:maxIndex >= n-1

代码为:

bool canJump(int A[], int n) {    int maxIndex = 0;    for(int i=0; i<n; i++) {        if(i>maxIndex || maxIndex>=(n-1)) break;        maxIndex = max(maxIndex, i+A[i]);    }     return maxIndex>=(n-1) ? true : false;}

两种效率其实差不多,都是线性O(n).

0 0
原创粉丝点击