您的位置:首页 > 其它

leetcode: Jump Game II

2013-11-21 13:40 260 查看
http://oj.leetcode.com/problems/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.)


思路

对这种题还有什么好说的呢?动态规划!以给定的数组为例(从0开始计数),第3格走1步可以到第4格,第2格最多走1步到不了第4格,第1格最多可以走3步也能到第4格,第0格最多走2步到不了第4格。那么我们只要比较一下到第1格和第3格哪个需要的步数较少,然后加1就可以了。

class Solution {
public:
int calcSteps(int A[], int position, vector<int> &steps) {
if (-1 != steps[position]) {
return steps[position];
}

int min = INT_MAX;

for (int i = position - 1; i >= 0; --i) {
if ((i + A[i]) >= position) {
if ((calcSteps(A, i, steps) + 1) < min) {
min = steps[i] + 1;
}
}
}

steps[position] = min;

return min;
}

int jump(int A[], int n) {
vector<int> steps(n, -1);

steps[0] = 0;
for (int i = 1; i <= min(A[0], n - 1); ++i) {
steps[i] = 1;
}

calcSteps(A, n - 1, steps);

return steps[n - 1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: