【Leetcode】55.Jump Game
2017-03-30 01:18
351 查看
Description:
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.
Example:
A = [2,3,1,1,4], return true.A = [3,2,1,0,4], return false.
思路:
本题的目标是判断能否到达最后最后一个点,那么可以这么进行分析:如果采用最少的跳跃步骤就能到达最后一个点,那么采用数量比最少步骤更多的步骤也一定能到达。这意味着我们可以优先选择跳跃步骤少的来进行尝试,即每个位置选取跳的最远的距离(maximum jump length)。这符合贪心算法的使用条件。因此,给定一个位置(pos),如果从这个位置能够跳到比这个位置更远的地方,那么将最远的那个位置视为当前位置,否则,让当前位置向前移动一格,再进行判断。还有一个重要判断条件是如果当前位置比下一个进行跳跃的位置还要远,那说明这个数组无法到达终点。以下是使用C++的实现过程:
bool canJump(vector<int>& nums) { int pos = 0; for (int next=0; next<nums.size() && pos<=next; next++){ if(nums[next] > 0) next = next+nums[next]; } if(next==nums.size()) return true; else return false; }
相关文章推荐
- LeetCode 55.Jump Game
- LeetCode-55.Jump Game
- leetcode - 55.Jump Game
- [leetcode] 55.Jump Game
- LeetCode Game of Life(位操作)
- Leetcode | Jump Game I && II
- LeetCode 292. Nim Game (取物游戏)
- LeetCode | Jump Game II
- Jump Game II leetcode java
- Leetcode 55. Jump Game
- 【一天一道LeetCode】#292. Nim Game
- leetcode之Game of Life 问题
- LeetCode: Jump Game Total 解题报告
- LeetCode 45 Jump Game II 题解
- leetcode — jump-game-ii
- [LeetCode39]Jump Game II
- LeetCode Jump Game
- leetcode 55. Jump Game
- LeetCode45 Jump Game II
- LeetCode: Jump Game II