leetcode 365. 水壶问题
题目详情
题目链接
有两个容量分别为 x升 和 y升 的水壶以及无限多的水。请判断能否通过使用这两个水壶,从而可以得到恰好 z升 的水?
如果可以,最后请用以上水壶中的一或两个来盛放取得的 z升 水。
你允许:
装满任意一个水壶
清空任意一个水壶
从一个水壶向另外一个水壶倒水,直到装满或者倒空
- 示例 1:
输入: x = 3, y = 5, z = 4
输出: True- 示例 2:
输入: x = 2, y = 6, z = 5
输出: False
我的代码
class Solution {
public:
set<pair<int , int>> results;
int M;
int m;
void getAllResults(int first, int second) {
if (results.count(make_pair(first, second)) == 1) {
return;
}
results.insert(make_pair(first, second));
getAllResults(M, second);
getAllResults(first, m);
getAllResults(0, second);
getAllResults(first, 0);
if (first + second <= m) {
getAllResults(0, first + second);
} else {
getAllResults(first + second - m, m);
}
if (first + second <= M) {
getAllResults(first + second, 0);
} else {
getAllResults(M, first + second - M);
}
}
bool canMeasureWater(int x, int y, int z) {
if ((x == z) || (y == z) || ((x + y) == z)) {
return true;
}
if ((x % 2 == 0) && (y % 2 == 0) && (z % 2 != 0)) {
return false;
}
if (x + y < z) {
return false;
}
M = max(x, y);
m = min(x, y);
getAllResults(0, 0);
for (auto result: results) {
if ((result.first == z) || (result.second == z) || (result.first + result.second == z)) {
return true;
}
}
return false;
}
};
问题
这个代码有问题,内存溢出,无法通过。
我的成绩
执行结果:执行出错
一些想法
- 本道题我用的比较暴力的手段,但内存溢出,尴尬。。。
题目解答
执行用时为 0 ms 的范例
class Solution {
public:
int gcd(int a,int b){
if(b==0) return a;
return gcd(b,a%b);
}
bool canMeasureWater(int x, int y, int z) {
if(z==0) return true;
if(x==z||y==z) return true;
if(x==y&&x!=z||x+y<z) return false;
int n=gcd(x,y);
if(z%n==0) return true;
return false;
}
};
思考
- 数学功底要求过高,根本想不到。。。