贪心:
题目描述:
给出一个非负整数数组,你最初在数组第一个元素的位置
数组中的元素代表你在这个位置可以跳跃的最大长度
你的目标是用最少的跳跃次数来到达数组的最后一个元素的位置
例如
给出数组 A =[2,3,1,1,4]
最少需要两次才能跳跃到数组最后一个元素的位置。(从数组下标为0的位置跳长度1到达下标1的位置,然后跳长度3到数组最后一个元素的位置)
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. (Jump1step from index 0 to 1, then 3 steps to the last index.)
输入描述:
输出描述:
示例1:
输入:
输出:
代码:
public class Solution {
public int jump(int[] A) {
int[] dp = new int[A.length]; // dp存放都到各点的最小步数
for (int i = 0; i < dp.length; i ++) {
int maxPosition = Math.min(i + A[i], A.length - 1); // 从i点出发能走的最远距离
for (int j = i + 1; j <= maxPosition; j ++) {
if(dp[j] == 0) dp[j] = dp[i] + 1; // 如果位置没被走过,则到达j点的步数为dp[i]+1
}
if(dp[A.length - 1] != 0) break; // 当第一次到达终点时,肯定是到达终点最短的步数
}
return dp[A.length - 1];
}
}