[LeetCode] Jump Game

[Problem]

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.


[Analysis]
动态规划问题。使用bool dp[1:n]数组,dp[i]表示从A[i]可以跳到A[n],从n-1~1更新数组。
对于dp[i],令step = 1~A[i],只要存在一个step,使得dp[i+step]=true,则dp[i]=true。
step可以从1~A[i]按step++的方式递增,但是这样在Large Judge时会TLE,更好的方法是:
如果dp[i+step]=false,即从i跳一个长度为step的一跳后,仍然无法从A[i+step]跳到A[n],那么直接从A[i+step]能够到达最远的地方的后面一位开始跳,即step += A[i+step] + 1。

[Solution]

class Solution {
public:
bool canJump(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n <= 0)return true;
bool mark[n];
memset(mark, false, sizeof(mark));
mark[n-1] = true;
for(int i = n-2; i >= 0; --i){
int j = 1;
while(j <= A[i]){
if(i + j == n - 1){
mark[i] = true;
break;
}
else if(i + j > n - 1){
break;
}
else{
mark[i] = mark[i+j];
if(mark[i] == true){
break;
}
}
j += A[i+j] + 1;
}
}
return mark[0];
}
};


说明:版权所有,转载请注明出处。 Coder007的博客
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值