## Sunday, November 23, 2014

### [LeetCode] Jump Game I, II

Jump Game I

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`.

Jump Game II

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.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = `[2,3,1,1,4]`
The minimum number of jumps to reach the last index is `2`. (Jump `1` step from index 0 to 1, then `3` steps to the last index.)

1. 能跳到位置i的条件：i<=maxIndex。
2. 一旦跳到i，则maxIndex = max(maxIndex, i+A[i])。
3. 能跳到最后一个位置n-1的条件是：maxIndex >= n-1

 ``` 1 2 3 4 5 6 7 8 9 10 11``` ```class Solution { public: bool canJump(int A[], int n) { int maxIndex = 0; for(int i=0; imaxIndex || maxIndex>=(n-1)) break; maxIndex = max(maxIndex, i+A[i]); } return maxIndex>=(n-1) ? true : false; } }; ```

d[k] = max(i+A[i])     d[k-2] < i <= d[k-1]

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14``` ```class Solution { public: int jump(int A[], int n) { int curMax = 0, njumps = 0, i = 0; while(curMax

#### 1 comment:

1. my jump game solution using backward or forward:
class Solution:
# @param {integer[]} nums
# @return {boolean}
def canJump(self, nums):
n = len(nums)
last = n-1
for i in range(2,n+1):
if n-i + nums[-i] >= last:
last = n-i
return last == 0

class Solution:
# @param {integer[]} nums
# @return {boolean}
def canJump(self, nums):
reachable = 0
for i in range(len(nums)):
if i > reachable: return False
reachable = max(reachable, i+nums[i])
return True

URL: http://traceformula.blogspot.com/2015/08/jump-game.html