LeetCode 45 Jump Game II 区间DP
作者:互联网
Given an array of non-negative integers nums
, 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.
You can assume that you can always reach the last index.
Solution
很容易想到 \(dp[i]\) 表示以 \(i\) 结尾时的最小步数,考虑如何转移:
可以发现正向的 \(dp\) 比较容易:
点击查看代码
class Solution {
public:
int jump(vector<int>& nums) {
int MAX = 9999999;
int dp[10005];
int n = nums.size();
for(int i=0;i<n;i++)dp[i] = MAX;
dp[0] = 0;
if(n==1)return 0;
else{
for(int i=0;i<n;i++){
for(int ach = i+1;ach <= i+nums[i] && ach<n;ach++){
dp[ach] = min(dp[ach],1+dp[i]);
}
}
return dp[n-1];
}
}
};
标签:Jump,nums,int,index,jump,45,II,array,dp 来源: https://www.cnblogs.com/xinyu04/p/16212064.html