[LeetCode] 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.
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.)
1 class Solution { 2 private: 3 int f[100000]; 4 public: 5 int jump(int A[], int n) { 6 // Start typing your C/C++ solution below 7 // DO NOT write int main() function 8 int maxPos = 0; 9 f[0] = 0; 10 11 for(int i = 0; i <= maxPos; i++) 12 { 13 int pos = i + A[i]; 14 if (pos >= n) 15 pos = n - 1; 16 17 if (pos > maxPos) 18 { 19 for(int j = maxPos + 1; j <= pos; j++) 20 f[j] = f[i] + 1; 21 maxPos = pos; 22 } 23 24 if (maxPos == n - 1) 25 return f[n-1]; 26 } 27 } 28 };
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步