LeetCodes——55. Jump Game【DP】

题目要求

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.
给定一个数组A,数组中的每个数表示站在该位置上能跳跃的最大步数。判断是否能够到达最后一个数,若能则返回true,不能则返回false。

解题思路

由于当前位置上是否能到达取决于前面各个点的数值,因此可以考虑用动态规划来做,建立一个DP数组:

vector<bool> dp(n,false);//n表示数组大小,初始化为false。
dp[i]表示数组的第i个位置是否能够到达,能则为true,不能则为false

该dp数组的状态转移方程为:

dp[i] = dp[j] && (i-j) <=nums[j];(j<i)
j位置可到达,并且i位置可从j位置到达。
若dp[i]为true,则不用再去检查i是否可从其他位置上到达,可直接break节省时间。

dp[n-1]则表示数组的最后一个位置是否能到达。

代码

class Solution {
public:
    bool canJump(vector<int>& nums) {
        vector<bool> dp(nums.size(),false);
        dp[0] = true;
        for (int i=1;i<nums.size();i++){
            for (int j=i-1;j>=0;j--){//一定要从后往前找,可节省时间。
                dp[i] = dp[j] && (i-j) <=nums[j];
                if (dp[i] == true){
                    break;
                }
            }
        }
        return dp[nums.size()-1];
    }
};

最后结果

75 / 75 test cases passed.
Status: Accepted
Runtime: 14 ms

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值