LeetCode45 Jump Game II【贪心】

来源:互联网 发布:历年粮食进出口数据 编辑:程序博客网 时间:2024/05/29 18:33

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 is2. (Jump1step from index 0 to 1, then3steps to the last index.)


有了之前jump game的铺垫,本以为这个题能快速的想到解法,然而还是卡了好几天orz

题目改成求最少步数了,开始想到是向前递推,每一步是由前一步来得,然而无论空间复杂度还是时间复杂度都太高。

看了自己思路的标称,有三个变量now存储当前位置,pre存储右侧前一位置,cnt存储步数

开始我在想,利用贪心的话,虽然局部是最优但是总体不一定最优啊,但是反过来想,这种贪心是基于从最终位置的,既然now可以到达,那么now~pre的所有点都可以到达pre


class Solution {public:    int jump(int A[], int n) {        int pre=0,now=n-1,cnt=0;        if(pre==now) return 0;//一定有解        while(true)        {            cnt++;            pre=now;            for(int i=n-2;i>=0;i--)            {                if(A[i]+i>=pre)                    now=i;            }            if(now==0) return cnt;        }    }};


0 0
原创粉丝点击