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.)
Note:
You can assume that you can always reach the last index.
class Solution {
public:
int jump(vector<int>& nums) {
return jumpBFS(nums);
}
// DFS
// pos >= nums.size() - 1
int jump(const vector<int>& nums,int pos) {
if (pos >= nums.size() - 1) {
return 0;
}
int steps_min = INT_MAX - 1;
for (int i = pos + 1; i <= nums[pos]+ pos && i < nums.size(); i++) {
int steps_cur = jump(nums, i) + 1;
if (steps_cur < steps_min) {
steps_min = steps_cur;
}
}
return steps_min;
}
// BFS
// O(n), take care i
int jumpBFS(const vector<int>&nums) {
if (nums.size() < 2) {
return 0;
}
int steps = 0;
int cur_max = 0;
int next_max = 0;
int i = 0;
while (cur_max - i + 1 > 0) {
steps++;
for (; i <= cur_max && i< nums.size(); i++) {
next_max = max(next_max, i +nums[i]);
if (next_max >= nums.size()- 1) {
return steps;
}
}
cur_max = next_max;
}
return steps;
}
// DP
int jumpDP(const vector<int>&nums) {
if (nums.size() < 3) {
return nums.size() - 1;
}
vector<int>min_steps(nums.size(), INT_MAX);
min_steps[0] = 0;
for (int i = 1; i < nums.size();i++) {
for (int j = 0; j < i; j++) {
if (j + nums[j] >= i&& min_steps[j] + 1 < min_steps[i]) {
min_steps[i] = min_steps[j]+ 1;
}
}
}
return min_steps[nums.size() - 1];
}
};