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);
                }
            }
        }
    };
  • 相关阅读:
    Hive_进阶
    日志分析_统计每日各时段的的PV,UV
    Sqoop_mysql,hive,hdfs导入导出操作
    Sqoop_ 简单介绍
    Sqoop_ 从 hive 导到mysql常遇九问题总结(转)
    MySql_设置编码
    Linux_MySql_yum_安装
    Hive_DDL与DML
    UI自动化持续化集成
    HDU 5073 数学题
  • 原文地址:https://www.cnblogs.com/727713-chuan/p/3333009.html
Copyright © 2011-2022 走看看