LC55 Jump Game

可以设置一个变量记录能到达最右边的位置,如果该位置大于数组长度则返回true。否则每前进一步,更新下这个能到达最右边的位置变量。

或者可以用逆向思维,要达到最后一个,首先必须能达到前面位置中的某一个。这里采用逆向法。

 1 class Solution {
 2 public:
 3     bool judge(vector<int>& nums, int index)
 4     {
 5         if(index==0)
 6             return true;
 7         int testi=index-1;
 8         while(testi>=0)
 9         {
10             if(nums[testi]+testi>=index)
11             {
12                 return judge(nums,testi);
13             }
14             testi--;
15         }
16         return false;
17     }
18     bool canJump(vector<int>& nums) {
19         if(nums.size()==0||nums.size()==1)
20             return true;
21         int length=nums.size();
22         return judge(nums,length-1);
23     }
24 };
View Code

 

posted @ 2016-03-13 20:42  vaevaevae  阅读(158)  评论(0编辑  收藏  举报