LeetCode 55. Jump Game
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 55. Jump Game相关的知识,希望对你有一定的参考价值。
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(); } };
以上是关于LeetCode 55. Jump Game的主要内容,如果未能解决你的问题,请参考以下文章