Leetcode——365. 水壶问题
经典倒水问题,如果实际操作过的话,很容易知道与最大公约数有关。
例如 x = 12, y = 21,可按顺序得到 12L、21L、33L、9L、18L、6L、15L、3L。
很显然除 0L 和 33L 特殊外,其余均为 3 的倍数,而 3 即为 x, y 的最大公约数。
这就是Bezout's Lemma(裴蜀定理、贝祖定理)。
class Solution {
public:bool canMeasureWater(int x, int y, int target) {if(target < 0 || target > x + y){return false;}if(target == 0 || target == x + y){return true;}if(target % gcd1(x, y) == 0){return true;}return false;}int gcd1(int x, int y){return y ? gcc(y, x % y) : x;}int gcd2(int x, int y){int t;while(y){t = x % y;x = y;y = t;}return x;}
};