Jump Game

Description:

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.

Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

思路分析:

1.动态规划

这是自己能想到的第一个方法。假设flag[i][j]表示从A[i]到A[j]是否可达,那么原问题可形式化为:


 

代码如下所示:

bool canJump(vector<int>& nums) {
        //用动态规划求解,runtime error!
        assert(!nums.empty());
        int n = nums.size();
//如果nums中不包含0则说明从第一个元素到最后一个元素一定是可达的
        bool isExitZero = false;
        for (int i = 0; i < n; ++i)
        {
            if (nums[i] == 0)
            {
                isExitZero = true;
                break;
            }
        }
        if (!isExitZero)
            return true;
         //nums包含0的情况   
        bool flag[MAX][MAX] = {true};//flag[i][j]表示从nums[i]是否能到nums[j]
        for (int i = 2; i <= n; ++i)
        {//长度为2,3,...,n的数字串
            for (int j = 0; j <= n-i; ++j)
            {//判断flag[j][k],j到k需要i-1步
                int k = j+i-1;
                if (nums[j] == 0)
                    flag[j][k] = false;
                else if (nums[j] >= i-1)
                    flag[j][k] = true;
                else
                {
                    flag[j][k] = false;
                    for (int m = 1; m <= nums[j]; ++m)
                    {
                        if (flag[j+m][k])
                        {
                            flag[j][k] = true;
                            break;
                        }
                    }
                }
            }
        }
        return flag[0][n-1];
    }

显然,上述代码时间和空间效率都比较低,在leetcode中运行也存在runtime error的问题!虽然知道该问题应该可以用贪心算法求解,但不知怎么证明该问题的贪心选择性质。


2.贪心算法

从网络上看到的方法。主要思想是用一个变量currentMaxStep_i表示当处于位置i时还能走的最大步数,则只要在到达位置n-1前它不小于0,则说明可达。代码如下:

bool canJump(vector<int>& nums) {
        assert(!nums.empty());
        int n = nums.size();
      int currentMaxStep = nums[0]; 
       for (int i = 1; i < n; ++i)
       {
           if (currentMaxStep<=0)
                return false;
            else
            {
                currentMaxStep--;
                currentMaxStep = max(currentMaxStep, nums[i]);//体现贪心选择性质
            }
       }
        return true;
}

总结:主要是对贪心选择性质理解不深刻,不能从一个问题迅速判断出是否含有贪心选择性质。

原文地址:https://www.cnblogs.com/happygirl-zjj/p/4574621.html