[leetcode] 45. Jump Game II 解题报告

来源:互联网 发布:sql注入视频教程下载 编辑:程序博客网 时间:2024/05/12 01:51

题目链接:https://leetcode.com/problems/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.)


本题是一个动态规划题目,保存一个最大可到达的距离,并设置一个数组来保存到达每个位置最短的步数,即当前的位置加上当前最大可走的步数,如果本次更新了最大距离,则同样更新从上一个最大距离到这次最大距离之间位置的步数,要注意边界条件,就是最大到达距离超出了数组长度的时候要做一个判断。

代码如下:

class Solution {public:    int jump(vector<int>& nums) {        if(nums.size() ==0) return 0;        int len = nums.size(), Max = 0;        vector<int> dp(len, 0);        for(int i = 0; i < len; i++)        {            if(i+nums[i] <= Max) continue;            for(int j = Max+1; j <= min(i+nums[i], len-1); j++)                dp[j] = dp[i] + 1;            Max = i+nums[i];        }        return dp[len-1];    }};



0 0
原创粉丝点击