水壶问题

题目描述:力扣

解题思路:参考自链接

一、使用bfs模拟6种倒水的操作

  1. 将水壶1的水倒满;
  2. 将水壶1的水清空;
  3. 将水壶2的水倒满;
  4. 将水壶2的水清空;
  5. 将水壶1的水倒入水壶2中,知道水壶2满了或者水壶1没水了就停止倒;
  6. 将水壶2的水倒入水壶1中,知道水壶1满了或者水壶2没水了就停止倒;

而且,不同的操作,中间过程会有很多重复的状态。因此可以用一个HashSet来记录已经访问过的状态(x,y)

二、

可以使用数学方法贝祖定理;连接:https://leetcode-cn.com/problems/water-and-jug-problem/solution/shui-hu-wen-ti-by-leetcode-solution/

class Solution {
    public boolean canMeasureWater(int x, int y, int z) {
    if (z < 0 || z > x + y) {
        return false;
    }
    Set<Integer> set = new HashSet<>();
    Queue<Integer> q = new LinkedList<>();
    q.offer(0);
    while (!q.isEmpty()) {
        int n = q.remove();
        if (n + x <= x + y && set.add(n + x)) {
            q.offer(n + x);
        }
        if (n + y <= x + y && set.add(n + y)) {
            q.offer(n + y);
        }
        if (n - x >= 0 && set.add(n - x)) {
            q.offer(n - x);
        }
        if (n - y >= 0 && set.add(n - y)) {
            q.offer(n - y);
        }
        if (set.contains(z)) {
            return true;
        }
    }
    return false;
    }
}

 

public boolean canMeasureWater(int x, int y, int z) {
    if (z == 0) return true;
    if (x + y < z) return false;

    int big = Math.max(x, y);
    int small = x + y - big;

    if (small == 0) return big == z;


    while (big % small != 0) {
        int temp = small;
        small = big % small;
        big = temp;
    }
    return z % small == 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值