Jump Game II

来源:互联网 发布:atmega128p单片机 编辑:程序博客网 时间:2024/06/09 14:41

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)


问题分析,这个问题动态规划的话就得不偿失了,另一个思路是贪心+递归,假设给定序列是a1...an,对应的最短跳数序列是a1,ai,aj...ak,an,总共的步数是m,缩减下规模就是找从a1到ak步数为最小的序列。这就是递归了,而贪心表现为我们总是希望一步到位,就是找到一步就能达到目的地的点。

//code

int jump(int A[], int n) {if(n <= 1) return 0;for (int i = 0; i < n - 1; ++i){if(i + A[i] >= n - 1)return (jump(A, i + 1) + 1);}}


0 0