贪心算法题目
递归
int k = INT_MAX;
vector<int> nums1;
int jump(vector<int>& nums) {
nums1 = nums;
dfs(0,0);
return k;
}
//注意,如果不用nums1,而是直接将nums作为形参,当nums很大时,多次调用dfs会超时
void dfs(int cur, int step)
{
if (cur >= nums1.size() - 1)
{
k = step;
return;
}
int start,bound = 0;
for (int i = 1; i <= nums1[cur]; i++)
{
if(cur+i >= nums1.size() - 1)
{
start = cur + i;
break;
}
if(cur+i+nums1[cur+i] > bound)
{
start = cur + i;
bound = cur+i+nums1[cur+i];
}
}
dfs(start,step+1);
return;
}
非递归
int jump(vector<int>& nums) {
int cur = 0;
int cnt = 0;
int flag = 1;
int start = 0;
if(nums.size()==1)
return 0;
while(flag)
{
int bound = 0;
for (int i = 1; i <= nums[cur]; i++)
{
if(cur+i >= nums.size() - 1)
{
flag = 0;
break;
}
if(cur+i+nums[cur+i] > bound)
{
start = cur + i;
bound = cur+i+nums[cur+i];
}
}
cur = start;
cnt++;
}
return cnt;
}