首页 > 其他 > 详细

LeetCode 55. Jump Game

时间:2016-07-05 20:48:44      阅读:260      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/gavinxing/p/5644751.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!