zoukankan      html  css  js  c++  java
  • [LeetCode] #45 Jump Game II

    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.

    Your goal is to reach the last index in the minimum number of jumps.

    For example:
    Given array A = [2,3,1,1,4]

    The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

    本题是跳跃问题,利用动态规划求解,每次记录最远到达的距离和步数。时间:16ms。代码如下:

    class Solution {
    public:
        int jump(vector<int>& nums) {
            size_t n = nums.size();
            if (n == 0 || n == 1)
                return 0;
            int maxstep = nums[0], step = 1;
            if (maxstep >= n - 1)
                return 1;
            for (int i = 1; i < n; i++){
                if (maxstep == 0)
                    return -1;
                maxstep--;
                if (maxstep < nums[i]){
                    maxstep = nums[i];
                    step++;
                }
                if (maxstep + i >= n - 1)
                    return step;
            }
            return -1;
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    C++---使用类
    C++---函数
    C++---指针和引用
    C++---面向对象
    C++---数组
    C++---条件结构和循环结构
    C++---变量、数据类型和运算符
    C++---初识C++
    MySQL---什么是事务
    MySQL---char和varchar的区别
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4584581.html
Copyright © 2011-2022 走看看