Leetcode之Jump Game问题

来源:互联网 发布:php 析构函数的用法 编辑:程序博客网 时间:2024/06/05 23:51

问题描述:

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

问题来源:Jump Game (详细地址:https://leetcode.com/problems/jump-game/description/)

思路:

    先来讲讲题目的意思吧,大致翻译一下:给定一个一维数组,其中的元素都是非负整数,我们最开始处于数组的最开始位置,数组中的元素代表你能往前移动的最大的步数,最后需要确定的是能不能到达数组的最后一个位置。

    相信读完题目,大部分人自然而然就想到了动态规划(Dynamic programming)的思想了,当然也有人说是贪心(Greedy algorithm),每一步取得局部最优结果,最后希望取到全局最优.好吧,好像都能讲的通。下面我采用的是一个局部变量(local)和一个全局变量(global)。

local:当前位置能够跳到哪;

global:截止到当前位置,能够跳到的最大位置,相比local来讲,global更加强调的是全局的意思,而不是当下(好像确实贪心靠谱些哈)

代码:




 







原创粉丝点击