leetcode:Jump Game II

来源:互联网 发布:java zxing 二维码 编辑:程序博客网 时间:2024/05/16 14:49
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.)

Note:
You can assume that you can always reach the last index.


题目如上,这里我们假设了总能够到达最后一个点。
个人认为,这道题最关键的一个点就是明白,当找到第一个可以到达终点的点时,他就是相对jump数最少的点。其后的所有点的jump数一定大于等于第一个点的jump数。比如【2,3,1,1,4】,不理解的读者可以自己尝试一下。从3到4,一步,而从4之前的1到4,至少你需要跳到1先,这个过程经过了3,所以他的jump数一定不会比3低。
明白了这一点,我们就可以开始尝试解题。思路是用一个reach函数来记录当前能跳到的最远点,然后当reach达到最远点的时候判定跳完,另外使用一个count数组来记录跳到每一个点的步数,步数等于跳到该点的最小jump数加1。代码如下:
int jump(vector<int>& nums) {
        int i = 0;
        int n = nums.size();
        int count[n];
        for(int i = 0; i < n; i++){                                                //初始化count数组
            count[i] = 1000000;
        }
        count[0] = 0;
        for (int reach = 0; i < n && i <= reach; ++i){
            reach = max(i + nums[i], reach);                            //判定reach的最远距离
            if(reach <= n - 1){                                                   //这里是为了防止count数组越界
                count[reach] = min(count[i] + 1, count[reach]);
            }
            else
                count[n - 1] = min(count[i] + 1, count[n - 1]);
        }
        return count[n - 1];
    }
这道题依旧是利用的贪心算法,“贪心”的地方是到每一次最远跳时都实现最少的jump。一步一步,到达终点时便是最少jump。
个人见解,如有不足请留言指教。
0 0
原创粉丝点击