[leetcode]45. Jump Game II 跳棋遊戲2 C++/PYTHON實現【hard難度】
題目
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.)
翻譯一下 是jump gamehttp://blog.csdn.net/zl87758539/article/details/51694895那個題目派生出來的。
之前那個是問你能不能跳到最後一個,現在是給你一個數組,肯定能跳到最後,問你最少需要多少步。
其實思路差不多的,之前用貪心,比如說n個數,第i個數跳的最遠記下來,
現在肯定也要記,只不過是,記每一步跳的最遠,我們設一個
第0個位置,最遠能跳到2,
第1個位置
第2個位置
程式碼如下:
C++
class Solution {
public:
int jump(vector<int>& nums) {
int L = nums.size();
if (L == 0 ||L ==1)return 0;
int G = nums[0],Gstep = G,R=1;
for(int i = 1;i < L -1; i++){
G = max((nums[i]+i),G);
if(i>=Gstep){
Gstep=G;R++;
}
if(Gstep>=L-1)return R;
}
return R;
}
};
PYTHON
class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
L = len(nums)
if L in [0,1]:
return 0
G = nums[0]
Gs = G
R = 1
for i in range(1,L-1):
G=max(nums[i]+i,G)
if i >= Gs:
Gs = G
R+=1
if Gs>=L-1:
return R
return R
“`