LeetCode 55. Jump Game

题目描述

出处 https://leetcode.com/problems/jump-game/description/

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.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.


分析

  1. 方法一:通过循环的方法,从终点开始,记录可以到达终点的最前一个点,如果与出发点相同,则可以到达终点,否则不可到达。
  2. 方法二:对方法一进行优化,只对 nusm[i] == 0 的情况进行处理,(若 nums[i] != 0 则说明可以到达点),当 nusm[i] == 0 时,进行判断前方的点是否可以跳过这的点达到下一个点,可以比方法一少计算一些,加快了计算速度。
    例如:nums = [4,3,2,1,0,1] -------- nums[4]不可以跳过
    nums = [4,3,2,2,0,1] -------- nums[4]可以跳过
  3. 方法三:通过递归的方法,使用贪心策略,加快计算速度。

最终结果

方法一:

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int des = nums.size()-1, len = nums.size();
        
        for (int i = len-1; i >= 0 ; i--) {
            if (i + nums[i] >= des) {
                if (i < des) des = i;
            }
        }
        
        return des == 0;
    }
};

方法二:

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int len = nums.size();
        bool flag = true;
        
        for (int i = len-2; i >= 0 ; i--) {     
            if (nums[i] == 0) {
                flag = false;
                for (int j = i-1; j >= 0 ;j--) {
                    if (j + nums[j] > i) {
                        flag = true;
                        break;
                    }
                }
                if (flag == false)
                    return false;
            }
        }
        
        return flag;
    }
};

方法三:

class Solution {
public:
	bool canJump(vector<int>& nums) {
		int len = nums.size();
		bool* dp = new bool[len];
		memset(dp, false, len);

		return jump(nums, len - 1, dp);
	}

	bool jump(vector<int>& nums, int n, bool* dp) {
		if (n == 0) {
			if (dp[n] == false)
				dp[n] = true;

			return dp[n];
		}

		for (int i = n - 1; i >= 0; i--) {
			if (i + nums[i] >= n) {
				if (dp[i] == false)
					dp[i] = jump(nums, i, dp);

				return dp[i];
			}
		}

		return dp[n];
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

妙BOOK言

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值