时间复杂度过高,o(n2)超时了:
class Solution {public: int jump(vector & nums) { int length = nums.size(); if(length <= 0) return 0; vector result(length); result[0] = 0; bool flag[length]; flag[0] = true; for(int i = 1;i < length;i++) flag[i] = false; for(int i = 1;i < length;i++){ int min_num = 0x7fffffff; for(int j = i-1;j >= 0;j--){ if(flag[j] == false) continue; if(flag[j] == true && nums[j] >= i-j){ if(result[j]+1 < min_num){ min_num = result[j] + 1; flag[i] = true; } } } result[i] = min_num; } return result[length-1]; }};
把上面代码简化,依旧是超时
class Solution {public: int jump(vector & nums) { int length = nums.size(); if(length <= 0) return 0; vector result(length); result[0] = 0; for(int i = 1;i < length;i++) result[i] = -1; for(int i = 1;i < length;i++){ int min_num = 0x7FFFFFFF; for(int j = i-1;j >= 0;j--){ if(result[j] != -1 && nums[j] >= i-j){ result[i] = result[j] + 1; if(result[i] < min_num) min_num = result[i]; } } if(min_num != 0x7FFFFFFF) result[i] = min_num; else result[i] = -1; } return result[length-1]; }};
用贪心算法做,时间复杂度只有0(n)
class Solution {public: int jump(vector & nums) { int n = nums.size(); if(n <= 0) return 0; int lastReach = 0; int reach = 0; int step = 0; for(int i = 0; i < n && i <= reach; i++) { if(i > lastReach) { step++; lastReach = reach; } reach = max(nums[i]+i, reach); } if(reach < n-1) return 0; else return step; }};
推导过程:
两个讲解博客:
http://blog.csdn.net/cinderella_niu/article/details/42804559
http://www.cnblogs.com/boring09/p/4231771.html