[C++]LeetCode: 104 Jump Game II (局部最优和全局最优法)

来源:互联网 发布:打数字软件 编辑:程序博客网 时间:2024/05/29 15:09
题目:

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

思路:这道题目和Jump Game思路类似。只不过这次,我们不仅要判断是否能够到达数组末尾(终点),同时要求出最小的跳跃次数。这次我们依然使用“局部最优和全局最优法”,不过这次维护的全局最优要分成两个变量:step最优和step-1步最优(假设当前步数是step步),如果我们的坐标 走到了超过step-1步最远达到的位置lastReach,也就是说step-1步无法达到这个当前位置 i,这时我们更新步数,将step加1。这里比较难理解的就是,reach始终维护的是step最远能达到的距离,因为reach = max(local, reach),并不是每一次都更新,只有在超出步数范围所能达到的最远距离才更新,所以当step-1步不能达到当前位置i时,需更新lastReach = reach,同时更新步数。

复杂度:时间复杂度O(N), 空间O(1)

Attention:

1. 注意还是要判断是否能达到终点,如果不能返回0,题目中并没有指出数组一定能达到终点。

 if(reach < n-1)            return 0;        else            return step;
2.三个维护的变量,初始化都从0开始,因为第一步所能到达的reach取决于A[0],应该在循环中一起更新,否则step等变量会出现错误。
 int lastReach = 0; int reach = 0; int step = 0;

AC Code:

class Solution {public:    int jump(int A[], int n) {        if(n == 0) return 0;        int lastReach = 0;        int reach = 0;        int step = 0;                for(int i = 0; i < n && i <= reach; i++)        {            if(i > lastReach)            {                step++;                lastReach = reach;            }            reach = max(A[i]+i, reach);        }                if(reach < n-1)            return 0;        else            return step;    }};
动态规划时面试中非常重要的类型,一般面试不会过于复杂,主要是考察思想还有边界等特殊情况的考虑,考虑问题是否完整全面,重点掌握几个经典的题目,Jump Game,Maximum Subarray, Maximum Product Subarray等,还有本题。


0 0
原创粉丝点击