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

posted @ 2021-07-24 21:28  牛有肉  阅读(89)  评论(0编辑  收藏  举报