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.
很容易想到 \(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]; } } };