您的位置:首页 > 其它

Leetcode: Jump Game II

2014-02-16 13:47 501 查看
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.)

第一反应,这回总该用DP了吧,吭哧吭哧,还是超时。。。优化呀优化,总算过了。

class Solution {
public:
int jump(int A[], int n) {
vector<int> dp(n, n);
dp[n-1] = 0;
for (int i = n - 2; i >= 0; --i) {
if (i + A[i] >= n - 1) {
dp[i] = 1;
continue;
}

for (int j = A[i]; j > 0; --j) {
dp[i] = min(dp[i], dp[i+j] + 1);
if (dp[i] <= 2) {
// the minimum steps should be 2
break;
}
}
}

return dp[0];
}
};其实啊,还是O(n)时间O(1)空间就可以,除了DP,不是还有Greedy算法嘛 - 关键是想法呀。用两个变量指示上次和当前最大可达的范围,一旦i大于上次最大可达的范围,表明需要用当前最大可达的范围来更新,以便i可以继续递增。

class Solution {
public:
int jump(int A[], int n) {
int prev = 0, cur = 0, steps = 0;
for (int i = 0; i < n; ++i) {
if (i > cur) {
// can't reach the last index
return -1;
}
if (i > prev) {
prev = cur;
++steps;
}
cur = max(cur, i + A[i]);
}

return steps;
}
};加上一点优化,如果当前可达的最大范围到了数组结尾,退出循环。

class Solution {
public:
int jump(int A[], int n) {
int prev = 0, cur = 0, steps = 0;
for (int i = 0; i < n; ++i) {
if (i > cur) {
// can't reach the last index
return -1;
}
if (i > prev) {
prev = cur;
++steps;
}
cur = max(cur, i + A[i]);
if (cur >= n - 1) {
if (i != n - 1) {
++steps;
}
break;
}
}

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