【Jump Game】cpp

题目:

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.

代码:

class Solution {
public:
        bool canJump(vector<int>& nums)
        {
            return Solution::dfs(nums, 0);
        }
        static bool dfs(vector<int>& nums, int index)
        {    
            if ( index>=nums.size()-1 ) return true;
            if ( nums[index]==0 ) return false;
            for ( int i = nums[index] ; i >= 1; --i ) 
            {
                if ( Solution::dfs(nums, index+i) ) return true; 
            }
            return false;
        }
};

tips:

随手写了一个DFS Solution,结果是对的但是超时,shit...

====================================

由于不会Greedy的算法,一心想写一个dp solution,结果最后dp没写成,写成了个greedy;不过代码还是很简洁和高效的:

class Solution {
public:
        bool canJump(vector<int>& nums)
        {
            int max_jump = 0;
            max_jump = std::max(max_jump, nums[0]);
            for ( int i = 0; i<=max_jump; ++i )
            {
                if ( max_jump>=nums.size()-1 ) return true;
                max_jump = std::max(max_jump, i+nums[i]);
            }
            return false;
        }
};

tips:

算法的时间复杂度O(n),空间复杂度O(1)。

正常往后迭代变量,每次迭代变量后,维护一个max_jump(即走到元素i,已知可以走到最远的元素下标)。

如果下标大于等于nums.size()-1,则返回true;如果遍历到max_jump了,且没有到达nums.size()-1,则返回false。

后来想想能不能用dp或者dfs再解一次,但想来想去,dp或者dfs解法的核心无非还是变形的greedy,没有太大意思。完毕。

===============================================

第二次过这道题,直接写了greedy的AC了。

class Solution {
public:
    bool canJump(vector<int>& nums) {
            if ( nums.size()==0 ) return false;
            int maxLength = 0;
            for ( int i=0; i<=maxLength; ++i )
            {
                if ( i+nums[i]>maxLength )
                {
                    maxLength = i+nums[i];
                }
                if ( maxLength>=nums.size()-1 ) return true;
            }
            return maxLength>=nums.size()-1;
    }
};

 

posted on 2015-05-29 19:50  承续缘  阅读(218)  评论(0编辑  收藏  举报

导航