首页 > 代码库 > [leetcode]Jump Game II
[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 is2
. (Jump 1
step from index 0 to 1, then 3
steps to the last index.)
基本思路:
用一个数组保存到index的最小的步数。 如果新的走法可以使得到index的最小步数变小,就更新之。最后返回对last index的最小步数。同时可以设置变量记录到目前为止可以到达的最远的index,用于剪枝。具体请看代码:
代码:
int jump(int A[], int n) { //C++ if(n == 1) return 0; int head = 0; vector<int> record(n,n); record[0] = 0; for(int i = 0; i < n; i++) { if(A[i] + i > head) { head = A[i] +i; for(int j = 1; j < n-i&&j <= A[i]; j++) if(record[i+j] > record[i]+1 ) { record[i+j] = record[i]+1; if(i+j == n-1) return record[i]+1; } } } return record[n-1]; }
[leetcode]Jump Game II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。