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
.
分析:贪心思想,记录在当前位置还可以走的次数,没跳一次,减少一步,如果当前位置可以跳跃的次数比原来剩下的大,则更新
class Solution {
public:
bool canJump(int A[], int n) {
if(A == NULL || n <= 0)return false;
int currentLeftStep = A[0],i;
for(i = 1;i < n;++i)
{
if(--currentLeftStep < 0)return false;
currentLeftStep = max(currentLeftStep,A[i]);
}
return true;
}
};
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.)
分析:该题总体的框架是动态规划,但是使用简单的二维dp会发生超时,二维dp的思路是:设dp[i]表示节点i到目标节点需要跳跃的次数,则dp[i] = min{dp[j]+1},其中j > i && i可以跳跃到j。
class Solution { public: int jump(int A[], int n) { if(A == NULL || n <= 0)return 0; int i,j; vector<int> dp(n); for(i=n-1;i >= 0;--i)dp[i] = n-i-1;//初始化 for(i = n-2;i >= 0;--i) { for(j=i+1;j<=i+A[i] && j <= n;++j)dp[i] = min(dp[i],dp[j]+1); } return dp[0]; } };
改进:思路仍然是动态规划,只是这次加上的贪心的味道。设dp[i]表示跳跃到节点i需要的次数,则我们从前往后遍历来计算dp[i],比如有j < k < i三个节点,则根据前面的定义,dp[j]
< dp[k],则如果j可以跳到i,那么他的次数肯定小于k跳到i的次数,从而减少了计算的次数。
class Solution { public: int jump(int A[], int n) { if(n <= 0)return INT_MAX; vector<int> dp(n,INT_MAX);//dp[i]表示到节点i至少需要几次跳跃 dp[0] = 0; int i,j; for (i = 1;i < n;i++) { for (j = 0;j < i;j++) { if(A[j] + j >= i)//从节点j可以跳跃的最远距离 { if(dp[j] + 1 < dp[i]) { dp[i] = dp[j]+1;//找到的第一个一定是最小的 break; } } } } return dp[n-1]; } };