LeetCode Jump Game
class Solution { public: bool canJump(int A[], int n) { if (A == NULL || n < 1) return false; vector<int> sum(n, 0); int jump = A[n-1]; for (int i=n-2; i>=0; i--) { jump = A[i]; if (i + jump >= n - 1) { sum[i] = sum[i+1] + 1; continue; } int region = sum[i + 1] - sum[i + jump + 1]; sum[i] = sum[i+1] + (region > 0); } if (jump >= n-1) { return true; } else { return sum[0] - sum[jump] > 0; } } };
直接用dfs+记忆超时,关键在于判断从某一位置上进行的跳跃中,其范围内的这些位置中是否有可达终点的情况存在,用一个后缀和来表示,每发现一个可以达到终点的位置该位置的后缀和相比其他+1,这样可以通过将两个后缀和相减与0比较判断该范围内是否有可达终点的位置。
找到一个时间O(n)空间O(1)的方法,精妙许多
http://www.cnblogs.com/zhuli19901106/p/3568215.html
第二轮:
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
.
只知道以前有看到过这么个思路,不过自己写的太烦了:
// 16:01 class Solution { public: bool canJump(vector<int>& nums) { int len = nums.size(); if (len < 2) { return true; } int last = 0; while (last < len) { int jmp = nums[last]; if (jmp == 0) { return false; } int jmax = 0; int jidx = last + 1; for (int i=1; i<=jmp; i++) { int idx = i + last; if (idx >= len - 1) { return true; } if (jmax < i + nums[idx]) { jmax = i + nums[idx]; jidx = idx; } } last = jidx; } return true; } };
自己也写个链接里的:
1 // 16:26 2 class Solution { 3 public: 4 bool canJump(vector<int>& nums) { 5 int len = nums.size(); 6 int jmp_far = 0; 7 int current = 0; 8 9 for (int i=0; i<len; i++) { 10 if (jmp_far < i) { 11 return false; 12 } 13 if (jmp_far >= len - 1) { 14 break; 15 } 16 jmp_far = max(i + nums[i], jmp_far); 17 } 18 return true; 19 } 20 };
5.21 又一次,没有想到简单的,还是用了复杂的,不过也行
// 00:23 class Solution { public: bool canJump(vector<int>& nums) { int len = nums.size(); int si = 0; while (si < len) { int next = si; int far = si; int end = si + nums[si]; if (end >= len - 1) return true; for (int i=si+1; i<=end; i++) { if (nums[i] + i > far) { next = i; far = nums[i] + i; } } if (si == next) return false; si = next; } return si >= len; } };