2024.1.28每日一题

108 阅读1分钟

LeetCode

水壶问题

365. 水壶问题 - 力扣(LeetCode)

题目描述

有两个水壶,容量分别为 jug1Capacityjug2Capacity 升。水的供应是无限的。确定是否有可能使用这两个壶准确得到 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

思路

裴蜀定理表明,若存在整数a,b,使得ax+by=z成立,则z一定为x.y最大公因数的整数倍。

要确定是否能够得到 targetCapacity 升水,可以使用数学中的裴蜀定理(Bézout's identity)来解决。

在这个问题中,可以将裴蜀定理应用于 jug1Capacity 和 jug2Capacity,找到它们的最大公约数是否能够整除 targetCapacity。如果可以整除,那么就有解,否则无解。

代码

C++

class Solution {
public:
    int gcd(int a,int b){
        if(b == 0){
            return a;
        } else{
            return gcd(b,a % b);
        }
    }
​
    bool canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
       if(targetCapacity > jug1Capacity + jug2Capacity){
           return false;
       }
        int temp = gcd(jug1Capacity,jug2Capacity);
​
        return targetCapacity % temp == 0; 
    }
};

Java

class Solution {
    public int gcd(int a, int b){
        return b == 0 ? a : gcd(b, a % b);
    }
​
    public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
        if(targetCapacity > jug1Capacity + jug2Capacity){
            return false;
        }
        int temp = gcd(jug1Capacity,jug2Capacity);
        return targetCapacity % temp == 0;
    }
}

image-20240128092015543