45. 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.
Example:
Input: [2,3,1,1,4]
Output: 2
Explanation: 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.
Note:
You can assume that you can always reach the last index.
思路:
DP(自底向上),数组dp[]表示能够到达该位置最小的steps,有一点类似最短上升子序列。
#include<iostream>
#include<vector>
using namespace std;
int minJump(vector<int>& nums)
{
int* dp = new int[(nums.size())];
for(int i=1;i<(nums.size());i++) dp[i]=INT_MAX;
dp[0]=0;
for(int i=0;i<(nums.size());i++){
for(int j=i+1;j<=i+nums[i]&&j<(nums.size());j++){
if(dp[i]+1<dp[j]) dp[j]=dp[i]+1;
}
}
int ans = dp[(nums.size()-1)];
delete[] dp;
return ans;
}
int main(void)
{
vector<int> input;
int size;
while(cin>>size){
int num;
for(int i=0;i<size;i++){
cin>>num;
input.push_back(num);
}
cout<<minJump(input)<<endl;
}
return 0;
}
本文介绍了一种解决Jump Game II问题的算法,通过动态规划(自底向上)找到从数组起始位置到达末尾所需的最小跳跃次数。示例中,输入为[2,3,1,1,4],输出为2,解释了如何从索引0跳到索引1再跳到末尾。代码实现使用C++,并提供了完整的函数和主程序流程。
902

被折叠的 条评论
为什么被折叠?



