Jump Game

来源:互联网 发布:关键词快速排名软件 编辑:程序博客网 时间:2024/06/04 00:27

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.

思路:动态规划的思路,依次记录从它前面的点能否到它,用一维向量存储每步是否可达,判断是否可达时通过判断它前面一步是否可达,以及可达的这步到它是否可达。 这种方法每次判断当前是否可达时,最差的情况要判断它前面所有的元素,这样需要O(n^2)的时间复杂度。

class Solution {public:    bool canJump(int A[], int n) {        if (n==1) {            return true;        }                vector<bool> can (n, false);        can[0] = true;        for (int i = 1; i < n; i++)            for (int j = 0; j < i; j++){                if (can[j] == true && A[j] >= i-j){  //之前写的A[j]==i-j,报超时                    can[i] = true;                    break;                }            }                return can[n-1];    }};


2015-01-14

看到一种O(n)的思路,每步存两个变量,一个变量存放到目前为止能走到的最远距离(全局变量),另一个变量存从当前位置出发最远能走到哪里(局部变量)。这种做法不用动态规划来存每步是否可达,而是用reach是否大于i来判断是否能到达i这一步。

class Solution {public:    bool canJump(int A[], int n) {        if (A == NULL || n == 0) {            return false;        }                int reach = 0;        for (int i = 0; i <= reach && i < n; i++) {             reach = max(reach, A[i] + i);            if (reach >= n - 1) {                return true;            }        }                if (reach < n - 1) {            return false;        }                return true;    }};



0 0
原创粉丝点击