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

    当你看清人们的真相,于是你知道了,你可以忍受孤独
  • 相关阅读:
    Redis
    IDEA编码相关,解决yml编码错误导致的 java.nio.charset.MalformedInputException: Input length = 1
    文件上传和下载
    SpringBoot+Mybatis+Postman实现增删改查
    多态与反射
    正则表达式
    原码、反码、补码的用法和理解
    @Conditional & @Profile SpringBoot中自动化配置条件注解。
    Spring Boot 中的 Starter
    第一个项目~千寻在线水果商城
  • 原文地址:https://www.cnblogs.com/niuyourou/p/15056337.html
Copyright © 2020-2023  润新知