zoukankan      html  css  js  c++  java
  • Leetcode 403 青蛙过河 DP

      JAVA:

    public final boolean canCross(int[] stones) {
            int len = stones.length;
            return jump(stones, 0, 0, new HashMap<Long, Boolean>());
        }
    
        private final boolean jump(int[] stones, int currPosition, int currStep, Map<Long, Boolean> cache) {
            int len = stones.length;
            if (currPosition == len - 1) return true;
            Long key = ((long) currPosition << 32) | currStep;
            if (cache.containsKey(key)) return cache.get(key);
            if (currPosition == 0) {
                if (stones[1] > 1) return false;
                else return jump(stones, 1, 1, cache);
            }
            int nextPosition = currPosition + 1, nextStep = 0;
            boolean res = false;
            while (nextPosition < len && (nextStep = stones[nextPosition] - stones[currPosition]) <= currStep + 1) {
                if (Math.abs(nextStep - currStep) < 2 && jump(stones, nextPosition, nextStep, cache)) {
                    res = true;
                    break;
                }
                nextPosition++;
            }
            cache.put(key, res);
            return res;
        }

      JS DP:

    /**
     * @param {number[]} stones
     * @return {boolean}
     */
    var canCross = function (stones) {
        return jump(stones, 0, 0, new Map());
    };
    
    var jump = function (stone, currPosition, currStep, cache) {
        let len = stone.length;
        if (currPosition == len - 1) return true;
        let key = currPosition + "," + currStep, his;
        if (his = cache.get(key)) return his == 1 ? true : false;
        if (currPosition == 0) {
            if (stone[1] > 1) return false;
            return jump(stone, 1, 1, cache);
        }
        let nextPosition = currPosition + 1, nextStep;
        while (nextPosition < len && (nextStep = stone[nextPosition] - stone[currPosition]) < currStep + 2) {
            if (Math.abs(nextStep - currStep) < 2 && jump(stone, nextPosition, nextStep, cache)) {
                cache.set(key, 1);
                return true;
            }
            nextPosition++;
        }
        cache.set(key, 2);
        return false;
    }

    当你看清人们的真相,于是你知道了,你可以忍受孤独
  • 相关阅读:
    KD Tree
    Kmeans聚类算法
    考托业啊考托业,英语是硬伤啊!!!
    c++中xx.h和xx.cpp之间的联系
    vs2010常用快捷键
    径向基函数(RBF)
    Obj文件分析与读取
    Delaunay三角剖分中的LOP(Local Optimization Procedure)算法
    c++中冒号(:)的用法
    SVN在update时报com' is missing or not locked 的解决办法汇总
  • 原文地址:https://www.cnblogs.com/niuyourou/p/15056337.html
Copyright © 2011-2022 走看看