问题描述
只要能跳跃到终点,中间的过程不必深究
初步探究
既然过程是透明的,那么最容易想到的解法是BFS(广度优先搜索)避免重复访问,并在能够到达终点时提前结束搜索。但是该解法的时间复杂度仍然是O(n²),提交后得到的结果是超时,这让我开始重新思考问题。class Solution { public: bool canJump(vector<int>& nums) { int s = nums.size(); vector<bool> b(s); for (int i = 1; i < s; i++) b[i] = false; b[0] = true; queue<int> q; while (!q.empty()) q.pop(); q.push(0); while (!q.empty()) { int pos = q.front(); for (int j = 1; j <= nums[pos] && pos+j < s && !b[s-1]; j++) { if (b[pos+j]) continue; b[pos+j] = true; q.push(pos+j); } q.pop(); } return b[s-1]; } };
解法优化
问题的终极目的是判断能否到达终点,那么我们是不是可以逐步计算每个position能够到达的最远位置,并进行迭代就可以了呢?
class Solution { public: bool canJump(vector<int>& nums) { int i = 0, n = nums.size(); for (int reach = 0; i < n && i <= reach; ++i) reach = i+nums[i] > reach? i+nums[i] : reach; return i == n; } };
只要判断当前计算的position是否已经越过了当前能够到达的最远处reach,就能够排除Jump中断的情形。这种解法的时间复杂度仅为O(n),很好的解决了超时限制。如果该题没有这种限制,可能我以后碰到类似的问题还会一直使用BFS来解决。然而通过这次经历,我体会到贪心算法在时间复杂度和代码简洁性方面的优越,今后也要尽量避免被固有思维僵化。