标签:
这个题目是一个特殊的跳台阶问题,给定一个数组,每个数组里面存放的是该位置可以跳的步数,求出跳到最后位置所需要的最少的步数。我看到这个题目的时候脑子里面的第一印象是递归,递归去求解肯定是可以的,于是我写了下面的代码(结果是超时!)
解法一,递归查找,时间效率太低了。。。不行 class Solution { public: int jump(vector<int>& nums) { /* 数组里面的内容代表给位置所能跳的最大步数,找出跳到最后位置所需要的最少步数 */ int len = nums.size(); //vector<int> Spos; int first = nums[0]; int mintimes = 0; for (int i = 1; i <= first; ++i) { //int length = findAllsolv(nums, Spos, i); int times = findAllsolv(nums, i); if (i == 1) { mintimes = times; } else { if (mintimes > times) { mintimes = times; } } } return mintimes; } int findAllsolv(vector<int>& nums, int begin) { int times = 0; if (begin >= nums.size()) { return 0; } for (int i = 1; i <= nums[begin]; ++i) { int time = 1 + findAllsolv(nums, begin + i); if (i == 1) { times = time; } else { if (times > time) { times = time; } } } return times; } };
这种方法确实可行,不过实现的时候千万要记得越界的处理,稍不注意就可能错误,下面是我的代码:
class Solution { public: int jump(vector<int>& nums) { /*这类问题还是使用贪心算法*/ int pos = 0; int length = nums.size(); int index = 0; if (length == 0) { return 0; } while (index < length-1) { int next = 0; int begin = index; int onejump = 0; for (int i = 1; i <= nums[index]; ++i) { if (nums[index] >= length-1 || index + i >= length || index + nums[index + i] >= length) {// [1,3,2] // [1,2] // [2,3,1] //9, 6, 6, 2, 3, 1, 0, 9, 2, 7 if (index + nums[index] < length - 1) { ++pos; } next = length; break; } if (i + nums[index+i] > onejump) { next = i; onejump = i + nums[index + i]; } } ++pos; index += next; } return pos; } };结果如下:
标签:
原文地址:http://blog.csdn.net/zr1076311296/article/details/51438783