一開始想DP一步步迭代更新,求出跳到最後一個的最小步數,但是時間復雜度O(nk),會超時。
再一想,發現該題只需要返回能否到達最後一個,不需要最小步數,所以迭代時候只需要保留當前能夠走到的最遠距離tmpMax,時間復雜度降到O(n)。
class Solution {
public:
const int MAXVALUE = 1 << 30;
bool canJump(int A[], int n) {
int tmpMax = 0;
if (n == 1)
return true;
for (int i = 0; i < n - 1; i++)
{
if (i > tmpMax)return false;
if (tmpMax < i + A[i])
tmpMax = i + A[i];
if (tmpMax >= n - 1)
return true;
}
return false;
}
};