LeetCode-365-水壶问题 (不定次方程的整数解)

365. Water and Jug Problem

Description

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.

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

Example

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

Solution

问题转化为: 给定 n 个容器 a1, a2,…,an。 最后需要 m 单位的水。
即求
一次不定方程
a1*x1 + a2*x2 + ... + an*xn = m的整数解。

原问题中, 只有两个容器 x, y。方程变成: X*x1 + Y*y1 = Z是否有整数解。

Hint

  1. 判断二元一次不定式方程是否有整数解: X 和 Y 的最小公约数是否能被 Z 整除

  2. 求解最小公约数: 辗转相除法 或 更相减损术。

Code

class Solution {	// 水壶问题    x, y 的瓶子 => 得到容量为 z
public:
	// 辗转相除法求解最大公约数
    // a > b 的情况下:
    //     如果 a 能够整除 b, 则 b 为最大公约数.
    //     否则, 使用 b 和 (a 对 b 的余数)继续求解。
	int gcd(int a, int b) {
		return a % b == 0 ? b : gcd(b, a % b);
	}

	// 更相减损术
	// int gcd(int a, int b) {
	// 	if (a == b) return a;
 //        if (a > b) return gcd(a-b, b);
 //        else return gcd(b-a, a);
	// }

    bool canMeasureWater(int x, int y, int z) {
        if (!z) return true;
        if (x + y < z) return false;
        if (!x) return z % y == 0;
        if (!y) return z % x == 0;
        return x > y ? (z % gcd(x, y) == 0) : (z % gcd(y, x) == 0);
    }
};
之前偶然看到的知乎回答:10L 瓶装水通过一个7L 瓶和3L 瓶平分成两瓶5L 水,有什么数学方法计算此类问题?

你可能感兴趣的:(Leetcode,算法)