最小跳数

Description:

描述:

This problem is a standard interview problem which has been featured in interview rounds of Adobe, Amazon, Oyo rooms etc.

此问题是标准的采访问题,已在Adobe,Amazon,Oyo房间等的采访回合中出现。

Problem statement:

问题陈述:

Given an array of integers where each element represents the max number of steps that can be made forward from that element. The task is to find the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then there is no way to move from there.

给定一个整数数组,其中每个元素代表可以从该元素进行的最大步数。 任务是找到到达数组末尾(从第一个元素开始)的最小跳转数。 如果元素为0,则无法从那里移动。

    Input:
The first line is T, total number of test cases.  
In the following 2*T lines,
Each test case has two lines.
First line is a number n denoting the size of the array.
Next line contains the sequence of integers a1, a2, ..., an
Output:
For each test case, in a new line, 
print the minimum number of jumps. 
If it's not possible to reach the end the print -1

Example:

例:

    Input:
1
11
1 3 5 3 1 2 6 0 6 2 4
Output:
4

Explanation:

说明:

    Let's first use greedy method.
According to greedy,
At first jump, 
it will move from index 0 to 1 
(arr[0]=1, so only 1 step jump is allowed)
At second jump,
It will move from index 1 to 4 
(arr[1]=3, so only 3 step jump is allowed)
At third jump,
it will move from index 4 to 6 
(arr[4]=2, so only 2 step jump is allowed)
Now arr[6]=0, so no more jump possible. It would result -1.
But, it's not the result. Thus, greedy fails. 

Since, the array value is maximum jump possible we have to check for all options up to maximum jumps. Obviously, a recursive function which would generate many overlapping sub problems. Let's check how we can solve the above example using recursion.

由于数组值是可能的最大跳转,因此我们必须检查所有选项,直到最大跳转为止。 显然,递归函数会产生许多重叠的子问题。 让我们检查一下如何使用递归解决上面的示例。

Minimum number of jumps (1)

After first jump (in this case only one move possible)

第一次跳动后(在这种情况下,只能移动一次)

Minimum number of jumps (2)

After second jump (I only took the best child (on solution path) of the recursion tree, you can try all)

第二次跳转后(我只带了递归树上最好的孩子(在解决方案路径上),可以尝试全部)

Minimum number of jumps (3)

After third jump (I only took the best child (on solution path) of the recursion tree, you can try all)

第三次跳转后(我只带了递归树上最好的孩子(在解决方案路径上),可以尝试全部)

Minimum number of jumps (4)

After fourth jump (That's end)

第四跳之后(结束)

Minimum number of jumps (5)

So, answer is 4.

答案是4。

Let's check the DP approach to solve the above problem.

让我们检查一下DP方法来解决上述问题。

Solution approach:

解决方法:

    1)  If the starting index has value 0 then we can't reach the end 
if the array size is more than 1, so return -1.
2)  If array size is 1, we are at the end already, so return 1 
which is minimum jump.
3)  Initialize DP[n]  with all elements having value INT_MAX
4)  for i=0 to n-1
for j=i+1 to maximum of(n-1,j+arr[i])
//i.e,last index or upto theindex maximum jump can reach
dp[j]=minimum(dp[j],dp[i]+1)
where dp[i]+1=one jump added with jumps required to reach index i 
end for
end for
// not updated in the loop refers that reach end is not possible
5)  if dp[n-1]==INT_MAX 
return -1
else
return dp[n-1]

C++ Implementation:

C ++实现:

#include <bits/stdc++.h>
using namespace std;
int min(int x,int y){
return (x<y)?x:y;
}
int minimumjumps(vector<int> arr,int n){
if(n==1)
return 1;
if(arr[0]==0)
return -1;
int dp[n];
for(int i=0;i<n;i++)
dp[i]=INT_MAX;
dp[0]=0;
for(int i=0;i<n;i++){
for(int j=i+1;j<=((i+arr[i])>(n-1)?(n-1):(i+arr[i]));j++){
dp[j]=min(dp[j],dp[i]+1);
}
}
return dp[n-1];
}
int main()
{
int t,n,item;
cout<<"output -1 if reaching end not possible\n";
cout<<"Enter number of testcases\n";
scanf("%d",&t);
for(int i=0;i<t;i++){
cout<<"Enter array size\n";
scanf("%d",&n);
vector<int> a;
cout<<"Enter elements:\n";
for(int j=0;j<n;j++){
scanf("%d",&item);
a.push_back(item);
}
int result=minimumjumps(a,n);
cout<<"Result is: ";
if(result==INT_MAX)
cout<<-1<<endl;
else
cout<<result<<endl;
}
return 0;
}

Output

输出量

output -1 if reaching end not possible
Enter number of testcases
1
Enter array size
11
Enter elements:
1 3 5 3 1 2 6 0 6 2 4
Result is: 4

翻译自: https://www.includehelp.com/icp/minimum-number-of-jumps.aspx

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/540655.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

BE的完整形式是什么?

工学学士 (BE: Bachelor of Engineering) BE is an abbreviation of Bachelor of Engineering. It is a bachelors degree program for under graduation in engineering and the duration of this course is 4 years. It is provided in many countries like India, Canada, S…

史上最详细Windows版本搭建安装React Native环境配置

说在前面的话: 感谢同事金晓冰倾情奉献本环境搭建教程 之前我们已经讲解了React Native的OS X系统的环境搭建以及配置&#xff0c;鉴于各大群里有很多人反应在Windows环境搭建出现各种问题&#xff0c;今天就特意更新一贴来说明。关于os x环境搭建以及react native入门学习资料…

Web浏览器端通过https 使用mqtt通讯

做的产品简介 这次需要做一个web端的上课平台&#xff0c;有音视频通讯&#xff0c;有白板(画板)功能&#xff0c;有文字通讯等。技术点 音视频通讯需要走Webrtc需要跟ios, android, windows, mac 客户端互联互通一般通讯通过mqtt协议MQTT简介 MQTT&#xff08;Message Queuing…

vga显示模式_VGA的完整形式是什么?

vga显示模式VGA&#xff1a;视频图形阵列 (VGA: Video Graphics Array) VGA is an abbreviation of "Video Graphics Array". VGA是“视频图形阵列”的缩写 。 It is a three-row 15-pin DE-15 connector display hardware developed by IBM in 1987. It was first …

【iCore4 双核心板_FPGA】例程十一:FSMC总线通信实验——独立地址模式

实验原理&#xff1a; STM32F767上自带FMC控制器&#xff0c;本实验将通过FMC总线的地址独立模式实现STM32与FPGA 之间通信&#xff0c;FPGA内部建立RAM块,FPGA桥接STM32和RAM块&#xff0c;本实验通过FSMC总线从STM32向 RAM块中写入数据&#xff0c;然后读取RAM出来的数据进行…

http 412 precondition failed

2019独角兽企业重金招聘Python工程师标准>>> 今天在谷歌浏览器上刷新页面的时候&#xff0c;出现了 如下失败信息&#xff1a; HTTP 412 (Precondition Failed) 想想当时的动作是在发送ajax请求失败之后&#xff0c;再刷新&#xff0c;就会出现上面的失败问题。百度…

Python | Pyplot标签

There are the following types of labels, 标签有以下几种&#xff0c; 1)X轴贴标 (1) X-axis labelling) plt.xlabel(Number Line)# Default labellingplt.xlabel(Number Line, colorgreen)#Font colour Changedplt.xlabel(Number Line, colorGreen, fontsize15)#Font size …

MySQL Index Condition Pushdown

2019独角兽企业重金招聘Python工程师标准>>> 一、Index Condition Pushdown简介 ICP&#xff08;index condition pushdown&#xff09;是mysql利用索引&#xff08;二级索引&#xff09;元组和筛字段在索引中的where条件从表中提取数据记录的一种优化操作。ICP的思…

java.util (Collection接口和Map接口)

1&#xff1a;Collection和Map接口的几个主要继承和实现类 1.1 Collection接口 Collection是最基本的集合接口&#xff0c;一个Collection代表一组Object&#xff0c;即Collection的元素&#xff08;Elements&#xff09;。一些Collection允许相同的元素而另一些不行。一些能排…

asp.net MVC5为WebAPI添加命名空间的支持

前言 默认情况下&#xff0c;微软提供的MVC框架模板中&#xff0c;WebAPI路由是不支持Namespace参数的。这导致一些比较大型的项目&#xff0c;无法把WebApi分离到单独的类库中。 本文将提供解决该问题的方案。 微软官方曾经给出过一个关于WebAPI支持Namespace的扩展&#xff0…

python无符号转有符号_Python | 散布符号

python无符号转有符号There are multiple types of Scatter Symbols available in the matplotlib package and can be accessed through the command marker. In this article, we will show some examples of different marker types and also present a list containing all…

在eclipse中启动Tomcat访问localhost:8080失败项目添加进Tomcat在webapp中找不到

软件环境&#xff1a;Eclipse oxygen&#xff0c; Tomcat8.5 #在eclipse中启动Tomcat访问localhost:8080失败 在eclipse中配置tomcat后&#xff0c;打开tomcat后访问localhost:8080后无法出现登陆成功的界面,即无法出现下面的界面 在eclipse中的servers状态栏中双击tomcat&…

程序员简历工作模式_简历的完整形式是什么?

程序员简历工作模式简历&#xff1a;简历 (CV: Curriculum Vitae) The CV is an abbreviation of Curriculum Vitae. It is a written outline summary of a persons educational training and qualifications and his other experiences. It is an absolute profile of a cand…

ajax的访问 WebService 的方法

转自原文 ajax的访问 WebService 的方法 如果想用ajax进行访问 首先在web.config里进行设置 添加在 <webServices> <protocols> <add name "HttpPost" /> <add name "HttpGet" /> </protocols> </webServices> <s…

Hyperledger Fabric 1.0 从零开始(七)——启动Fabric多节点集群

5&#xff1a;启动Fabric多节点集群 5.1、启动orderer节点服务 上述操作完成后&#xff0c;此时各节点的compose配置文件及证书验证目录都已经准备完成&#xff0c;可以开始尝试启动多机Fabric集群。 首先启动orderer节点&#xff0c;切换至orderer.example.com服务器&#xff…

css中图片左右边距_CSS中的边距

css中图片左右边距CSS保证金属性 (CSS margin property) CSS Margins are used to space around any element, for this we use "margin" property in the CSS. CSS边距用于在任何元素之间留出空间&#xff0c;为此&#xff0c;我们在CSS中使用“ margin”属性 。 S…

js 实现网页显示倒计时

用 js 来实现网页显示倒计时效果 1 function checkTime( time ){2 var data new Data(); // 获取现在时间3 var nowData data.getTime(); // 转化成毫秒数4 var time ; // 结束的时间5 var t time - nowData ;6 var HH, mm , ss 0;7 var sta "…

ORACLE 物理读 逻辑读 一致性读 当前模式读总结浅析

在ORACLE数据库中有物理读&#xff08;Physical Reads&#xff09;、逻辑读&#xff08;Logical Reads&#xff09;、一致性读&#xff08;Consistant Get&#xff09;、当前模式读&#xff08;DB Block Gets&#xff09;等诸多概念&#xff0c;如果不理解或混淆这些概念的话&a…

arm tbh_TBH的完整形式是什么?

arm tbhTBH&#xff1a;说实话 (TBH: To Be Honest) TBH is an abbreviation of "To Be Honest". It is internet slang which generally used as an acronym or hashtag over the internet on social media networking sites like Facebook, Instagram, Twitter, Yo…

计数器数组_子数组计数

计数器数组Problem statement: 问题陈述&#xff1a; Given an array of N positive integers a1, a2, ..., an. The value of each contiguous subarray of a given array is the maximum element present in that subarray. The task is to return the number of subarrays…