LeetCode 365. Water and Jug Problem
考点 | 难度 |
---|---|
Math | Medium |
题目
You are given two jugs with capacities jug1Capacity and jug2Capacity liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly targetCapacity liters using these two jugs.
If targetCapacity liters of water are measurable, you must have targetCapacity liters of water contained within one or both buckets by the end.
Operations allowed:
Fill any of the jugs with water.
Empty any of the jugs.
Pour water from one jug into another till the other jug is completely full, or the first jug itself is empty.
思路
0
到x + y
之间的所有和gcd
的倍数
proof: https://leetcode.com/problems/water-and-jug-problem/discuss/83714/A-little-explanation-on-GCD-method.-C%2B%2BJavaPython
答案
class Solution:
def canMeasureWater(self, x, y, z):
gcd, r = max(x, y), min(x, y)
while r: gcd, r = r, gcd % r
return z == 0 or x + y >= z and z % gcd == 0