标签:
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
.
题意:给定一组数组,每个元素代表在此位置能够跳跃的最大距离,判断是否能够跳到最后一个下标。
有三种思路:
#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; }
标签:
原文地址:http://www.cnblogs.com/zxy1992/p/4279232.html