【Leetcode】Jump Game

红太狼 2022-06-18 09:00 252阅读 0赞

55. 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.

题目:给定一组非负的整数,初始时在数组中的第一个元素的位置。元素中的每一个元素表示当前位置可以跳的最大步数。需要决定是否能够达到最后一个位置。

例如,给定A=[2,3,1,1,4],返回真。给定A=[3,2,1,0,4],返回真。


解题思路
这道题目其实可以直接用动态规划:
设状态为f[i],表示从第0 层出发,走到A[i] 时剩余的最大步数,则状态转移方程为:
f[i] = max(f[i - 1], A[i - 1]) - 1, i > 0

  1. class Solution {
  2. public:
  3. bool canJump(vector<int>& nums) {
  4. int n = nums.size();
  5. vector<int> f(n, 0);
  6. f[0] = 0;
  7. for (int i = 1; i < n; i++) {
  8. f[i] = max(f[i - 1], nums[i - 1]) - 1;
  9. if (f[i] < 0) return false;;
  10. }
  11. return f[n - 1] >= 0;
  12. }
  13. };

发表评论

表情:
评论列表 (有 0 条评论,252人围观)

还没有评论,来说两句吧...

相关阅读

    相关 New Game

    New Game Description New game是在一个M\M的特殊棋盘(棋盘的第i行都标上了数字i)上进行的新式游戏。给定一个数字N,要求选手把一个棋子从

    相关 Flip Game

    这段代码还有问题,暂时记录下来,有时间再做修改。 [http://poj.org/problem?id=1753][http_poj.org_problem_id_1753

    相关 Nim Game

    一、题目   1、审题   2、分析     你先选,能选 1~3个砖头,对手在选 1~3个砖头。若你和对手都很聪明,且能拿到最后一块砖头的人胜利,给出砖头总数 ...