365. Water and Jug Problem (GCD or BFS) TBC

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

There are two methods to solve this problem : GCD(+ elementary number theory) --> how to get GCF, HCD,  BFS

Currently, I sove this by first method

1. how to compute GCD recursively

//get the GCD of two number s
    int GCD(int a, int b){
        if(a == 0) return b;
        if(b == 0) return a;
        return GCD(b,a%b);
    }

12, 8  -> 8,4 -> 4, 4 -> 4, 0

math solution

Bézout's identity (also called Bézout's lemma) is a theorem in the elementary theory of numbers:

let a and b be nonzero integers and let d be their greatest common divisor. Then there exist integers x
and y such that ax+by=d

In addition, the greatest common divisor d is the smallest positive integer that can be written as ax + by

every integer of the form ax + by is a multiple of the greatest common divisor d.

 

If a or b is negative this means we are emptying a jug of x or y gallons respectively.

Similarly if a or b is positive this means we are filling a jug of x or y gallons respectively.

x = 4, y = 6, z = 8.

GCD(4, 6) = 2

8 is multiple of 2

so this input is valid and we have:

-1 * 4 + 6 * 2 = 8

In this case, there is a solution obtained by filling the 6 gallon jug twice and emptying the 4 gallon jug once. (Solution. Fill the 6 gallon jug and empty 4 gallons to the 4 gallon jug. Empty the 4 gallon jug. Now empty the remaining two gallons from the 6 gallon jug to the 4 gallon jug. Next refill the 6 gallon jug. This gives 8 gallons in the end)

 

code: 

class Solution {
   public boolean canMeasureWater(int x, int y, int z) {
       //check the limitiation which x + y < z such as 3,4 , 8: notmeeting the requirement
       if(x+ y < z) return false;
       //check all 0
      System.out.println(GCD(x,y));
        //there is a theory about that
       //ax + by = gcd   z%gcd == 0 Bézout's identity 
       if(GCD(x,y) == 0) return z==0;
       else return (z%GCD(x,y)==0);
   }
    
    //get the GCD of two number s
    int GCD(int a, int b){
        if(a == 0) return b;
        if(b == 0) return a;
        return GCD(b,a%b);
    }
    
}

 

--------------------------------------------------------------------------------------------------------------------------------

BFS method

posted @ 2018-05-02 11:52  wz30  阅读(188)  评论(0编辑  收藏  举报