30
30
输出: False
31
31
</pre >
32
32
33
-
34
33
## 解法
35
34
36
35
<!-- 这里可写通用的实现逻辑 -->
37
36
37
+ 可以认为,每次操作只会让壶里的水带来 x 或者 y 的变化量。因此只要满足 ` ax + by = z ` 即可。
38
+
39
+ 根据裴蜀定理,` ax + by = z ` 有解,当且仅当 z 是 x,y 的最大公约数的倍数。所以我们只要找到 x,y 的最大公约数,然后判断 z 是否是这个最大公约数的倍数即可求得答案。
40
+
38
41
<!-- tabs:start -->
39
42
40
43
### ** Python3**
@@ -74,6 +77,16 @@ class Solution:
74
77
return False
75
78
```
76
79
80
+ ``` python
81
+ class Solution :
82
+ def canMeasureWater (self , jug1Capacity : int , jug2Capacity : int , targetCapacity : int ) -> bool :
83
+ if jug1Capacity + jug2Capacity < targetCapacity:
84
+ return False
85
+ if jug1Capacity == 0 or jug2Capacity == 0 :
86
+ return targetCapacity == 0 or jug1Capacity + jug2Capacity == targetCapacity
87
+ return targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0
88
+ ```
89
+
77
90
### ** Java**
78
91
79
92
<!-- 这里可写当前语言的特殊实现逻辑 -->
@@ -109,7 +122,7 @@ class Solution {
109
122
} else {
110
123
stk. offer(new int []{0 , cur1 + cur2});
111
124
}
112
-
125
+
113
126
}
114
127
return false ;
115
128
}
@@ -120,6 +133,64 @@ class Solution {
120
133
}
121
134
```
122
135
136
+ ``` java
137
+ class Solution {
138
+ public boolean canMeasureWater (int jug1Capacity , int jug2Capacity , int targetCapacity ) {
139
+ if (jug1Capacity + jug2Capacity < targetCapacity) {
140
+ return false ;
141
+ }
142
+ if (jug1Capacity == 0 || jug2Capacity == 0 ) {
143
+ return targetCapacity == 0 || jug1Capacity + jug2Capacity == targetCapacity;
144
+ }
145
+ return targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0 ;
146
+ }
147
+
148
+ private int gcd (int a , int b ) {
149
+ return b == 0 ? a : gcd(b, a % b);
150
+ }
151
+ }
152
+ ```
153
+
154
+ ### ** C++**
155
+
156
+ ``` cpp
157
+ class Solution {
158
+ public:
159
+ bool canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
160
+ if (jug1Capacity + jug2Capacity < targetCapacity) return false;
161
+ if (jug1Capacity == 0 || jug2Capacity == 0)
162
+ return targetCapacity == 0 || jug1Capacity + jug2Capacity == targetCapacity;
163
+ return targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0;
164
+ }
165
+
166
+ int gcd(int a, int b) {
167
+ return b == 0 ? a : gcd(b, a % b);
168
+ }
169
+ };
170
+ ```
171
+
172
+ ### ** Go**
173
+
174
+ ``` go
175
+ func canMeasureWater (jug1Capacity int , jug2Capacity int , targetCapacity int ) bool {
176
+ if jug1Capacity+jug2Capacity < targetCapacity {
177
+ return false
178
+ }
179
+ if jug1Capacity == 0 || jug2Capacity == 0 {
180
+ return targetCapacity == 0 || jug1Capacity+jug2Capacity == targetCapacity
181
+ }
182
+
183
+ var gcd func (a, b int ) int
184
+ gcd = func (a, b int ) int {
185
+ if b == 0 {
186
+ return a
187
+ }
188
+ return gcd (b, a%b)
189
+ }
190
+ return targetCapacity%gcd (jug1Capacity, jug2Capacity) == 0
191
+ }
192
+ ```
193
+
123
194
### ** ...**
124
195
125
196
```
0 commit comments