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;
    }

    当你看清人们的真相,于是你知道了,你可以忍受孤独
  • 相关阅读:
    线程同步:互斥锁,条件变量,信号量
    设计推荐系统
    寻找第K大的数
    算法思想
    LIS 最长递增子序列
    LeetCode Median of Two Sorted Arrays
    oracle查询所有初始化参数(含隐含参数)
    glibc 2.x release note
    spring boot log4j2与三方依赖库log4j冲突无法初始化问题解决方法
    spring boot @Scheduled未生效原因以及相关坑、及相对其他定时任务架构的优势
  • 原文地址:https://www.cnblogs.com/niuyourou/p/15056337.html
Copyright © 2011-2022 走看看