【leetcode】 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.

题意:给定一组数组,每个元素代表在此位置能够跳跃的最大距离,判断是否能够跳到最后一个下标。

有三种思路:

  • 正向从 0 出发,一层一层往右跳,看最后能不能超过最右下标,能超过,说明能到达,否则不能到达。
  • 逆向出发,一层一层递减,看能不能到达0.
  • 可以用动规,设状态为 f[i],表示从第 0 层出发,走到 A[i] 时剩余的最大步数,则状态转移方程为:f [i] = max(f [i − 1], A[i − 1]) − 1, i > 0
#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    bool canJump(int A[], int n) {
        int reach = 1;//the right most position can reach
        for(int i = 0; i < reach && reach < n; i++)
            reach = max(reach, i + 1 + A[i]);
        return reach >= n;
    }
    
    bool canJump1(int A[], int n) {
        if(n == 0)    return true;
        int left_most = n - 1;//the left most position can reach
        for(int i = n - 2; i >= 0; --i)
            if(i + A[i] >= left_most)
                left_most = i;
        return left_most == 0;
    }

    bool canJumpDp(int A[],int n){
        //f [i] = max(f [i − 1], A[i − 1]) − 1, i > 0
        vector<int> f(n, 0);//hold the state
        f[0] = 0; 
        for(int i = 1; i < n; ++i){
            f[i] = max(f[ i - 1], A[i - 1]) - 1;
            if(f[i] < 0)
                return false;
        }
        return f[n - 1] >= 0;
    }
};

int main()
{
    Solution s;
    int A1[] = {2,3,1,1,4};
    int A2[] = {3,2,1,0,4};
    cout << s.canJumpDp(A1, 5) << endl;
    cout << s.canJumpDp(A2, 5) << endl;
    return 0;        
}
原文地址:https://www.cnblogs.com/zxy1992/p/4279232.html