Leetcode 55. 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.

 

 1 public class Solution {
 2     public bool CanJump(int[] nums) {
 3         if (nums.Length < 1) return false;
 4         
 5         int maxReach = nums[0];
 6         int j = 1;
 7         while (j < nums.Length)
 8         {
 9             if (maxReach >= nums.Length - 1) return true;
10             if (maxReach < j) return false;
11             maxReach = Math.Max(maxReach, j + nums[j]);
12             j++;
13         }
14         
15         return true;
16     }
17 }

 

 

It can be also solved by DP.

 1 public bool CanJump(int[] nums) {
 2         if (nums.Length < 1) return false;
 3         var dp = new bool[nums.Length];
 4         dp[0] = true;
 5         
 6         int j = 1;
 7         while (j < nums.Length)
 8         {
 9             for (int i = j - 1; i >= 0; i--)
10             {
11                 dp[j] = dp[i] && (nums[i] >= j - i);
12                 if (dp[j]) break;
13             }
14             
15             if (!dp[j]) return false;
16             j++;
17         }
18         
19         return dp[dp.Length - 1];
20     }

 

posted @ 2017-11-09 05:28  逸朵  阅读(99)  评论(0)    收藏  举报