LeetCode解法汇总365. 水壶问题

 目录链接:

力扣编程题-解法汇总_分享+记录-CSDN博客

GitHub同步刷题项目:

https://github.com/September26/java-algorithms

原题链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台


描述:

有两个水壶,容量分别为 jug1Capacity 和 jug2Capacity 升。水的供应是无限的。确定是否有可能使用这两个壶准确得到 targetCapacity 升。

如果可以得到 targetCapacity 升水,最后请用以上水壶中的一或两个来盛放取得的 targetCapacity 升水。

你可以:

  • 装满任意一个水壶
  • 清空任意一个水壶
  • 从一个水壶向另外一个水壶倒水,直到装满或者倒空

示例 1: 

输入: jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4
输出: true
解释:来自著名的 "Die Hard"

示例 2:

输入: jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5
输出: false

示例 3:

输入: jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3
输出: true

提示:

  • 1 <= jug1Capacity, jug2Capacity, targetCapacity <= 106

解题思路:

本题适合深度优先搜索的思路去解决。

把桶1和桶2剩余的水量作为一种场景,基于这种场景有六种操作:

桶1或者桶2清空;

桶1或者桶2填满;

桶1倒入桶2或者桶2倒入桶1;

所以我们可以推演出6中新的场景,然后继续去搜索这6种场景。

为了避免场景的重复,我们设置一个set记录重复场景即可。

代码:

public class Solution365 {

    public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {

        Map map = new HashMap<>();
        Queue> queue = new ArrayDeque<>();
        checkAndAdd(map, queue, jug1Capacity, jug2Capacity);
        while (!queue.isEmpty()) {
            Pair poll = queue.poll();
            Integer key1 = poll.getKey();
            Integer key2 = poll.getValue();
            if (key1 == targetCapacity || key2 == targetCapacity || (key1 + key2) == targetCapacity) {
                return true;
            }
            //水桶1或者2清空
            checkAndAdd(map, queue, 0, key2);
            checkAndAdd(map, queue, key1, 0);
            //水桶1倒入水桶2,以及反向
            checkAndAdd(map, queue, Math.max(0, key1 - (jug2Capacity - key2)), Math.min(jug2Capacity, key1 + key2));
            checkAndAdd(map, queue, Math.min(jug1Capacity, key1 + key2), Math.max(0, key2 - (jug2Capacity - key1)));
            //装满一个水桶
            checkAndAdd(map, queue, jug1Capacity, key2);
            checkAndAdd(map, queue, key1, jug2Capacity);
        }
        return false;
    }

    private void checkAndAdd(Map map, Queue> queue, int jug1Capacity, int jug2Capacity) {
        String key = jug1Capacity + "_" + jug2Capacity;
        if (map.containsKey(key)) {
            return;
        }
        map.put(key, key);
        queue.add(new Pair<>(jug1Capacity, jug2Capacity));
    }
}

你可能感兴趣的:(编程题,leetcode,算法,职场和发展)