方法一:深度优先搜索
1 class Solution: 2 def canMeasureWater(self, x: int, y: int, z: int) -> bool: 3 stack = [(0, 0)] 4 self.seen = set() 5 while stack: 6 remain_x, remain_y = stack.pop() 7 if remain_x == z or remain_y == z or remain_x + remain_y == z: 8 return True 9 if (remain_x, remain_y) in self.seen: 10 continue 11 self.seen.add((remain_x, remain_y)) 12 # 把 X 壶灌满。 13 stack.append((x, remain_y)) 14 # 把 Y 壶灌满。 15 stack.append((remain_x, y)) 16 # 把 X 壶倒空。 17 stack.append((0, remain_y)) 18 # 把 Y 壶倒空。 19 stack.append((remain_x, 0)) 20 # 把 X 壶的水灌进 Y 壶,直至灌满或倒空。 21 stack.append((remain_x - min(remain_x, y - remain_y), remain_y + min(remain_x, y - remain_y))) 22 # 把 Y 壶的水灌进 X 壶,直至灌满或倒空。 23 stack.append((remain_x + min(remain_y, x - remain_x), remain_y - min(remain_y, x - remain_x))) 24 return False
官方题解,注释写的还是比较清楚的(虽然我看不太明白)。
方法二:贝祖定理
1 class Solution: 2 def canMeasureWater(self, x: int, y: int, z: int) -> bool: 3 if x + y < z: 4 return False 5 if x == 0 or y == 0: 6 return z == 0 or x + y == z 7 return z % math.gcd(x, y) == 0
这个没学过,执行效率比第一种方法要高。
参考:https://leetcode-cn.com/problems/water-and-jug-problem/solution/shui-hu-wen-ti-by-leetcode-solution/