zoukankan      html  css  js  c++  java
  • Jump Game

    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.

    先想到了动态规划,不过可惜大数据没有过,是一个从25000到0的递减一的数组,想试试贪心。

    动态规划:

    class Solution {
    public:
        bool canJump(int A[], int n) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            bool B[n];
            B[n-1] = true;
            for(int i = n-2;i>=0;i--)
            {
                int x = A[i];
                B[i] = false;
                if(i+x>n-1)
                    B[i] = true;
                else
                while(x!=0&&!B[i])
                {
                    if(B[i+x]==true)
                    B[i]=true;
                    x--;
                }
            }
            return B[0];
        }
    };

    贪心:

    class Solution {
    private: map<int,bool> record;    
    public:
        bool canJump(int A[], int n) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            record.clear();
            for(int i = 0;i<n;i++)
            {
                if(Jump(A,n,i))
                return true;
                if(A[i]==0)
                return false;
            }
            return false;
        }
        bool Jump(int A[],int n,int i)
        {
            if(A[i]+i>=n-1)
            {
                record[i] = true;
                return true;
            }
            else if(A[i]==0)
            {
                record[i] = false;
                return false;
            }
            else
            {
                map<int,bool>::iterator iter= record.find(i);
                if(iter!=record.end())
                return record[i];
                else
                {
                    return Jump(A,n,A[i]+i);
                }
            }
        }
    };
  • 相关阅读:
    生于忧患,死于安乐
    【网络流24题】骑士共存问题
    【网络流24题】最长不下降子序列问题
    【网络流24题】太空计划问题
    SG函数
    【网络流24题】餐巾计划问题
    【APIO2019】奇怪装置
    【HEOI2016/TJOI2016】游戏
    【SDOI2015】星际战争
    【CQOI2009】跳舞
  • 原文地址:https://www.cnblogs.com/727713-chuan/p/3333009.html
Copyright © 2011-2022 走看看