# [LeetCode] 365. Water and Jug Problem 水罐问题

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.

Example 1:

Input: jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4
Output: true
Explanation: The famous Die Hard example


Example 2:

Input: jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5
Output: false


Example 3:

Input: jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3
Output: true


Constraints:

• 1 <= jug1Capacity, jug2Capacity, targetCapacity <= 10^6

Credits:
Special thanks to @vinod23 for adding this problem and creating all test cases.

z = m * x + n * y

class Solution {
public:
bool canMeasureWater(int x, int y, int z) {
return z == 0 || (x + y >= z && z % gcd(x, y) == 0);
}
int gcd(int x, int y) {
return y == 0 ? x : gcd(y, x % y);
}
};

Github 同步地址：

https://github.com/grandyang/leetcode/issues/365

https://leetcode.com/problems/water-and-jug-problem/

https://leetcode.com/problems/water-and-jug-problem/discuss/83715/Math-solution-Java-solution

LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2016-06-30 08:55  Grandyang  阅读(13899)  评论(12编辑  收藏  举报