水壺問題(向水壺中倒z升水) Water and Jug Problem

問題:code

You are given two jugs with capacities x and y litres. There is an infinite amount of water supply available. You need to determine whether it is possible to measure exactly z litres using these two jugs.ip

If z liters of water is measurable, you must have z liters of water contained within one or both buckets by the end.ci

Operations allowed:leetcode

  • Fill any of the jugs completely 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: (From the famous "Die Hard" example)get

Input: x = 3, y = 5, z = 4
Output: True

Example 2:it

Input: x = 2, y = 6, z = 5
Output: False

解決:io

【題意】對於example1,有一個容量爲3升和一個容量爲5升的水罐,問咱們如何準確的稱出4升的水。先把5升水罐裝滿水,倒到3升水罐裏,這時5升水罐裏還有2升水,而後把3升水罐裏的水都倒掉,把5升水罐中的2升水倒入3升水罐中,這時候把5升水罐裝滿,而後往此時有2升水的3升水罐裏倒水,這樣5升水罐倒出1升後還剩4升即爲所求。class

https://discuss.leetcode.com/topic/49751/clear-explanation-of-why-using-gcd容器

① 這道問題其實能夠轉換爲有一個很大的容器,咱們有兩個杯子,容量分別爲x和y,問咱們經過用兩個杯子往裏倒水,和往出舀水,問能不能使容器中的水恰好爲z升。那麼咱們能夠用一個公式來表達:gc

z = m * x + n * y

其中m,n爲舀水和倒水的次數,正數表示往裏舀水,負數表示往外倒水。

題目中的例子能夠寫成: 4 = (-2) * 3 + 2 * 5,即3升的水罐往外倒了兩次水,5升水罐往裏舀了兩次水。那麼問題就變成了對於任意給定的x,y,z,存不存在m和n使得上面的等式成立。

根據裴蜀定理,ax + by = d的解爲 d = gcd(x, y),那麼咱們只要只要z % d == 0,上面的等式就有解,因此問題就迎刃而解了,咱們只要看z是否是x和y的最大公約數的倍數就好了,別忘了還有個限制條件x + y >= z,由於x和y不可能稱出比它們之和還多的水。

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

相關文章
相關標籤/搜索