标签:
Problem: https://leetcode.com/problems/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
.
Thought:
1. position i can be reached as well as exists 0 =< j < i is reachable and i - j <= nums[j] , the thought is right but time exceeded.
2. greedy , for position i , judge whether it is reachable (the maximun of i + nums[i] and reachable_last)
Code C++:
class Solution { //time exceeded public: bool canJump(vector<int>& nums) { vector<bool> valid (nums.size(), false); valid[0] = true; for (int i = 1; i < nums.size(); i++) { for (int j = 0; j < i; j++) { if (i - j <= nums[j] && valid[j]) { valid[i] = true; } } } return valid[nums.size() - 1]; } };
class Solution { public: bool canJump(vector<int>& nums) { int i = 0; for (int reach = 0; i < nums.size()&& i <= reach; i++) { reach =max(i + nums[i], reach); } return i == nums.size(); } };
标签:
原文地址:http://www.cnblogs.com/gavinxing/p/5644751.html