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);
                }
            }
        }
    };
  • 相关阅读:
    洛谷 P1981 表达式求值
    1696:逆波兰表达式
    C# winform选择文件、选择文件夹、打开文件
    建立二叉树的二叉链表存储结构(严6.70)
    二叉树的深度
    Sequence
    c++优先队列(priority_queue)用法详解
    二叉树的操作
    [清华集训2015]灯泡(浙江大学ZOJ 3203 Light Bulb)
    Go 和 Colly笔记
  • 原文地址:https://www.cnblogs.com/727713-chuan/p/3333009.html
Copyright © 2011-2022 走看看