问题陈述:给定一个长度为 N 的非负整数数组 A,您最初位于数组的第一个索引处。数组中的每个元素代表您在该位置的最大跳跃长度。返回到达最后一个索引所需的最小跳转次数。
输入:A = [2,3,1,1,4]
输出:2
解释:到达索引 4 的最短路径是索引 0 -> 索引 1 -> 索引 4,需要 2 次跳转。
以下是解决方案:
// M is the function that gives the required minimum jumps
// nums is the vector containing jumps (here I have used nums in place of array A).
// start denoting the starting index
// map(m) STL for memoization
int M(vector<int> &nums, int start, unordered_map<int, int>&m){
if(start == nums.size()-1){return 0;} // if we reach the last index then return 0.
if(start >= nums.size()){return INT_MAX;} // if we reach beyond last index then return some big value that can't be the answer.
if(nums[start] == 0){return INT_MAX;} // if in mid we get jump value = 0 then we cannot expect the min jump so again return some big value.
if(m[start] != 0){return m[start];} // if we already stored the value (calculated the answer) then return stored value
int ans = INT_MAX; // assuming initially answer to be some big value.
for(int i=1; i<=nums[start]; i++){ // jump can be made from 1 to maximum value of that element in array i.e. nums[start]
ans = min(ans, 1+M(nums, start+i, m)); // answer is minimum of previously calculated answer and 1 + allowed path (start + i).
m[start] = ans; // storing it in map.
}
return m[start]; // returning the stored value
}
我正在为上述解决方案获得 TLE。记忆后我无法弄清楚解决方案的时间复杂度。有人可以帮助我估计上述解决方案的时间复杂度。