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.
Analysis:
这道题也可以分解成子问题使用递归做。
但是下面的方法显然更简单一些,就是类似于动规的方法用reach来记录在当前位置能走到的最远范围。
Source Code(C++):

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

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

int main() {
    Solution sol;
    vector<int> v;
    bool res=false;
    v.push_back(2);v.push_back(3);v.push_back(1);v.push_back(1);v.push_back(4);
    res = sol.canJump(v);
    if (res){
        cout << "true" << endl;
    }
    else {
        cout << "false" << endl;
    }
    v.clear();
    v.push_back(3);v.push_back(2);v.push_back(1);v.push_back(0);v.push_back(4);
    res = sol.canJump(v);
    if (res){
        cout << "true" << endl;
    }
    else {
        cout << "false" << endl;
    }
    return 0;
}

你可能感兴趣的:(55. Jump Game)