Jump Game II

来源:互联网 发布:纵横公路预算软件 编辑:程序博客网 时间:2024/06/07 02:39

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.)

动态规划

class Solution {public:    int jump(int A[], int n){if (1 == n) return 0;vector<int> dp(n, -1);int curmax = 0;for (int i = 0; i < n - 1; i++)    {    if (i + A[i] > curmax){int tmp = i + A[i];for (int j = curmax + 1; j <= tmp && j <= n - 1; j++)dp[j] = i;curmax = tmp;if (curmax >= n - 1)break;}}int step = n - 1;int count = 0;while(step > 0){count++;step = dp[step];}return count;    }};


贪心

class Solution {public:    int jump(int A[], int n){if (1 == n) return 0;int step = 0;int curmax1 = 0;int curmax2 = curmax1 + A[curmax1];while(curmax1 < n - 1){if (curmax2 >= n - 1)break;step++;int tmp = 0;for (int i = curmax1; i <= curmax2 && i <= n - 1; i++)tmp = max(tmp, i + A[i]);curmax1 = curmax1 + A[curmax1];curmax2 = tmp;}return ++step;    }};





0 0