码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 55. Jump Game

时间:2016-07-05 20:50:02      阅读:203      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!