最小跳數

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.pswp.cn/news/540655.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/540655.shtml
英文地址,請注明出處:http://en.pswp.cn/news/540655.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

《Web安全之機器學習入門》一 第3章 機器學習概述

第3章 機器學習概述機器學習的概念非常多&#xff0c;從有監督到無監督&#xff0c;從聚類到回歸&#xff0c;從淺層學習到深度學習&#xff0c;從準確率到召回率&#xff0c;它們究竟是什么意思呢&#xff1f;本章將介紹最主要的幾個概念。不少機器學習初學者甚至包括業內老司…

ue 抗鋸齒 渲染序列失靈_最大的鋸齒形序列

ue 抗鋸齒 渲染序列失靈Problem statement: 問題陳述&#xff1a; Given a square matrix of size n x n, find the sum of the Zigzag sequence with the largest sum. A zigzag sequence starts from the top and ends at the bottom. Two consecutive elements of sequence…

團隊-團隊編程項目作業名稱-成員簡介及分工

成員&#xff1a;祁昊 分工&#xff1a;ui設計&#xff0c;美工&#xff0c;詳細設計。轉載于:https://www.cnblogs.com/qihao10086/p/7496101.html

python身份運算符_Python身份運算符

python身份運算符Identity operators are used to perform the comparison operation on the objects i.e. these operators check whether both operands refer to the same objects (with the same memory location) or not. 身份運算符用于對對象執行比較操作&#xff0c;即…

Oracle-Decode()函數和CASE語句的不同

Oracle-Decode()函數和CASE語句的區別&#xff1a; 具體示例如下&#xff1a; 1.CASE語句&#xff1a; SELECT CASE SIGN(5 - 5) WHEN 1 THEN Is Positive WHEN -1 THEN Is Negative ELSE Is Zero END FROM DUAL; 后臺實現&#xff1a; if (SIGN(5 – 5) 1) { Is Positive; } …

ai智能模式_AI的完整形式是什么?

ai智能模式AI&#xff1a;人工智能 (AI: Artificial Intelligence) AI is an abbreviation of "artificial intelligence", which occasionally called machine intelligence in the field of computer science. It is intelligence made understandable by machines…

centos6.5安裝python3.6

1、下載Python安裝包 wget https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tgz 2、解壓安裝包&#xff1a;tar -xzvf Python-3.6.0.tgz 3、進入安裝包路徑&#xff1a;cd Python-3.6.04、編譯安裝包 注意&#xff1a;prefix參數用于指定將Python安裝在新目錄&#xff…

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入門學習資料…

程序代碼錯誤檢測_錯誤檢測代碼

程序代碼錯誤檢測錯誤檢測代碼 (Error Detecting Codes) A group of bits is known as words, and these words move as an entity from one block to another in the digital system. While moving from one part to another within the system via transmission media, the b…

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出來的數據進行…

世界糧農組織五大健康食品_糧農組織的完整形式是什么?

世界糧農組織五大健康食品糧農組織&#xff1a;請注意 (FAO: For the Attention Of) FAO is an abbreviation of "For the Attention Of". FAO是“ For the Attention Of”的縮寫 。 It is an expression, which is commonly used in the Gmail platform. When a ma…

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 …

LTNS的完整形式是什么?

LTNS&#xff1a;很久沒看到 (LTNS: Long Time No See) LTNS is an abbreviation of "Long time, no see". LTNS是“長時間&#xff0c;看不見”的縮寫 。 It is an English phrase used when people meet and greet each other after a while when in between they…

MySQL Index Condition Pushdown

2019獨角獸企業重金招聘Python工程師標準>>> 一、Index Condition Pushdown簡介 ICP&#xff08;index condition pushdown&#xff09;是mysql利用索引&#xff08;二級索引&#xff09;元組和篩字段在索引中的where條件從表中提取數據記錄的一種優化操作。ICP的思…

ADBB的完整形式是什么?

ADBB&#xff1a;所有完成的再見 (ADBB: All Done Bye Bye) ADBB is an abbreviation to All Done Bye Bye. ADBB是All Done Bye Bye的縮寫。 Whenever a person wants to convey his message to another person, they use some sort of short-form in the text messages. ADB…

c 環境

系統ubuntu sudo apt-get install vim g openssh-server libgl1-mesa-dev檢查下安裝的版本gcc -v g -v make -v gdb -v 轉載于:https://blog.51cto.com/skinglzw/1964449