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);
                }
            }
        }
    };
  • 相关阅读:
    MT【319】分段递推数列
    MT【318】分式不等式双代换
    Centos7环境变量
    VI快捷键
    Centos7 开机自动运行命令
    Centos7 编辑本地DNS解析配置文件
    Centos7修改主机名
    xadmin 自定义过滤器选项
    Centos7网卡配置文件
    Centos7 挂载
  • 原文地址:https://www.cnblogs.com/727713-chuan/p/3333009.html
Copyright © 2011-2022 走看看