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.
Have you met this question in a real interview?
Yes
Example
A =
[2,3,1,1,4]
, return true
.
A =
[3,2,1,0,4]
, return false
.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class Solution { public: /** * @param A: A list of integers * @return: The boolean answer */ bool canJump(vector<int> A) { // write you code here if (A.empty() || A[0]==0) return false; int n=A.size(); vector<bool> tbl(n, false); tbl[0]=true; for (int i=1; i<n; i++){ for (int j=i-1; j>=0; j--){ if(tbl[j] && j+A[j]>=i ){ tbl[i]=true; break; } } } return tbl[n-1]; } }; |
No comments:
Post a Comment