leetcode--Jump Game
2017-05-02 21:16
302 查看
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.
解题思路:由于每层最多可以跳 A[i] 步,也可以跳 0 或 1 步,因此如果能到达最高层,则说明每一层都可以到达。有了这个条件,说明可以用贪心法。思路:正向,从 0 出发,一层一层网上跳,看最后能不能超过最高层,能超过,说明能到达,否则不能到达。
代码:
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.
解题思路:由于每层最多可以跳 A[i] 步,也可以跳 0 或 1 步,因此如果能到达最高层,则说明每一层都可以到达。有了这个条件,说明可以用贪心法。思路:正向,从 0 出发,一层一层网上跳,看最后能不能超过最高层,能超过,说明能到达,否则不能到达。
代码:
class Solution { public: bool canJump(vector<int>& nums) { int reach = 1; // 最右能跳到哪里 for (int i = 0; i < reach && reach < nums.size(); ++i) reach = max(reach, i + 1 + nums[i]); return reach >= nums.size(); } };
相关文章推荐
- LeetCode 98 Jump Game
- Leetcode之Jump Game问题
- [LeetCode] 55. Jump Game
- LeetCode 55 - Jump Game
- Leetcode: Jump Game
- [LeetCode]题解(python):055-Jump Game
- LeetCode——Jump Game
- LeetCode 055 Jump Game
- [leetcode]Jump Game
- [leetcode]Jump Game
- [LeetCode]Jump Game
- 动态规划小结 - 一维动态规划 - 时间复杂度 O(n),题 [LeetCode] Jump Game,Decode Ways
- 【leetcode】第55题 Jump Game 题目+解析+代码
- [leetcode刷题系列]Jump Game
- [Leetcode] jump game 跳跃游戏
- LeetCode -- Jump Game
- LeetCode:Jump Game
- [LeetCode] Jump Game
- [LeetCode] 55. Jump Game
- LeetCode-M-Jump Game