题目:

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) {
int max_jump=, next_max_jump=, min_step=;
for ( int i = ; i<=max_jump; ++i )
{
if ( max_jump>=nums.size()- ) break;
if ( max_jump < i+nums[i] ) next_max_jump = std::max(next_max_jump, i+nums[i]);
if ( i==max_jump )
{
max_jump = next_max_jump;
min_step++;
}
}
return min_step;
}
};

tips:

参考Jump Game的Greedy思路。

这道题要求求出所有可能到达路径中的最短步长,为了保持O(n)的解法继续用Greedy。

这道题的核心在于贪心维护两个变量:

max_jump:记录上一次跳跃能跳到最大的下标位置

next_max_jump:记录遍历所有max_jump之前的元素后,下一次可能跳到的最大下标位置

举例说明如下:

原始数组如右边所示:{7,0,9,6,9,6,1,7,9,0,1,2,9,0,3}

初始:max_jump=0 next_max_jump=0 min_step=1

i=0:next_max_jump=7  更新max_jump=7 更新min_step=1

i=1: 各个值不变

i=2: i+nums[i]=2+9=11>7 更新next_max_jump=11

i=3:i+nums[i]=3+6=9<11 不做更新

i=4: i+nums[i]=4+9=13>11 更新max_jump=13

...

i=7:i+nums[i]=7+7=14 >= nums.size()-1 返回min_step=2

完毕

==========================================

第二次过这道题,不太顺,大体复习了下思路。

class Solution {
public:
int jump(vector<int>& nums) {
if ( nums.size()== ) return ;
int ret = ;
int nextJump = ;
int maxLength = ;
for ( int i=; i<=maxLength; ++i )
{
if ( maxLength>=nums.size()- ) break;
nextJump = std::max(i+nums[i], nextJump);
if ( i==maxLength )
{
maxLength = nextJump;
ret++;
}
}
return ret;
}
};

==========================================

第三次过这道题,把代码改了一行,但是整体结构清晰了不少。

class Solution {
public:
int jump(vector<int>& nums) {
if (nums.size()<) return ;
int steps = ;
int local = ;
int next = local;
for ( int i=; i<=local; ++i )
{
next = max(next, i+nums[i]);
if ( i==local )
{
steps++;
local = next;
if ( local>=nums.size()- ) return steps;
}
}
return ;
}
};

next只负责看下一跳能够到哪。

什么时候更新local了,再判断能否跳到尾部。

【Jump Game II 】cpp的更多相关文章

  1. 【Word Break II】cpp

    题目: Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where e ...

  2. 【Unique Paths II】cpp

    题目: Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. H ...

  3. 【Path Sum II】cpp

    题目: Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the give ...

  4. 【Spiral Matrix II】cpp

    题目: Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. ...

  5. 【palindrome partitioning II】cpp

    题目: Given a string s, partition s such that every substring of the partition is a palindrome. Return ...

  6. 【Combination Sum II 】cpp

    题目: Given a collection of candidate numbers (C) and a target number (T), find all unique combination ...

  7. 【Word Ladder II】cpp

    题目: Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) ...

  8. 【Single Num II】cpp

    题目: Given an array of integers, every element appears three times except for one. Find that single o ...

  9. 【N-Quens II】cpp

    题目: Follow up for N-Queens problem. Now, instead outputting board configurations, return the total n ...

随机推荐

  1. JSP注释格式

    一.JSP注释格式来源 JSP是Sun Microsystems公司制定的一种服务器端动态网页技术的组件规范,其主体由HTML.CSS.JavaScript和Java拼凑组成. 正是因为JSP是一种组 ...

  2. python3基础05(有关日期的使用1)

    #!/usr/bin/env python# -*- coding:utf-8 -*- import timefrom datetime import datetime,timedelta,timez ...

  3. LeetCode Reverse Words in a String 将串中的字翻转

    class Solution { public: void reverseWords(string &s) { string end="",tem="" ...

  4. coursera_ML_1

    机器学习定义: A  computer program is said to leran from experience E with respect to some task T and some ...

  5. 如何在ABAP Netweaver和CloudFoundry里记录并查看日志

    Netweaver 要记录日志需要有一个checkpoint group,可以自行创建也可以使用标准的.这里我重用标准的group:DEMO_CHECKPOINT_GROUP. tcode SAAB, ...

  6. POJ 3280 Cheapest Palindrome(区间dp)

    dp[i][j]表示处理完i到j的花费,如果s[i] == s[j] 则不需要处理,否则处理s[i]或s[j], 对一个字符ch,加上ch或删掉ch对区间转移来说效果是一样的,两者取min. #inc ...

  7. Linux常用的200个命令总结分类

    ●目录操作命令(6 个) ls tree pwd mkdir rmdir cd   ●文件操作命令(7 个) touch cp mv rm ln find rename   ●文件查看及处理命令(21 ...

  8. A1043 Is It a Binary Search Tree (25 分)

    A Binary Search Tree (BST) is recursively defined as a binary tree which has the following propertie ...

  9. WebService简单入门

    写在前面的话: 当两个人碰面后,产生了好感,如果需要得到双方的信息,那么双方的交流是必不可少的!应用程序也如此, 各个应用程序之间的交流就需要WebService来作为相互交流的桥梁! 项目目的: 程 ...

  10. jsp页面:一个form,不同请求提交form

    需求:一个表单中有一个请求 action="url"发送数据地址: 在表单外有一个请求,请求form表单提交的数据 我们用js来写:通过每次请求传不同的action=url; 例如 ...