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

Jump Game

时间:2014-08-13 14:29:46      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   for   ar   art   

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.

一种比较直接方法就是暴力搜索所有可能情况,可以用dfs来实现,但这种方法是超时的。代码如下:

 1 class Solution {
 2 public:
 3     bool canJump(int A[], int n) {
 4         if(n == 0) return false;
 5         return dfs(A,n,0);
 6     }
 7     bool dfs(int A[], int n, int start){
 8         if(start >= n-1) return true;
 9         for(int i = 1; i <= A[start]; i++){
10             if(dfs(A,n,start+i)) return true;
11         }
12         return false;
13     }
14 };

 之后看了leetcode-cpp.pdf中的解法,发现可以用贪心算法来解。该题有这样一个性质,如果最后一个元素可以达到,那么所有元素都可以达到,根据这个性质我们可以用贪心算法。代码如下:

 1 class Solution {
 2 public:
 3     bool canJump(int A[], int n) {
 4         int reach = 1;
 5         for(int i = 0; i < reach && reach < n; i++){
 6             reach = max(reach, i+1+A[i]);
 7         }
 8         return reach >= n;
 9     }
10 };

 

Jump Game,布布扣,bubuko.com

Jump Game

标签:style   blog   color   os   io   for   ar   art   

原文地址:http://www.cnblogs.com/Kai-Xing/p/3907493.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!