• 【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;
        }
    };
  • 相关阅读:
    dijkstra算法模板 -- 最短路
    0-1背包
    POJ 1456-Supermarket(贪心+并查集)
    CodeForces 556C
    CodeForces
    POJ 2253-Frogger(Floyd变形)
    POJ 1251-Jungle Roads(最小生成树)
    HDU 1846-Brave Game(巴什博弈)
    HDU 1233-还是畅通工程(经典最小生成树)
    51Nod 1649-齐头并进(最短路dijkstra)
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4539326.html
Copyright © 2020-2023  润新知