@@ -64,6 +64,8 @@ class Solution:
64
64
if u == len (matchsticks):
65
65
return True
66
66
for i in range (4 ):
67
+ if i > 0 and edges[i - 1 ] == edges[i]:
68
+ continue
67
69
edges[i] += matchsticks[u]
68
70
if edges[i] <= x and dfs(u + 1 ):
69
71
return True
@@ -104,6 +106,9 @@ class Solution {
104
106
return true ;
105
107
}
106
108
for (int i = 0 ; i < 4 ; ++ i) {
109
+ if (i > 0 && edges[i - 1 ] == edges[i]) {
110
+ continue ;
111
+ }
107
112
edges[i] += matchsticks[u];
108
113
if (edges[i] <= x && dfs(u - 1 , x, matchsticks, edges)) {
109
114
return true ;
@@ -138,6 +143,7 @@ public:
138
143
if (u == matchsticks.size()) return true;
139
144
for (int i = 0; i < 4; ++i)
140
145
{
146
+ if (i > 0 && edges[i - 1] == edges[i]) continue;
141
147
edges[i] += matchsticks[u];
142
148
if (edges[i] <= x && dfs(u + 1, x, matchsticks, edges)) return true;
143
149
edges[i] -= matchsticks[u];
@@ -158,23 +164,62 @@ func makesquare(matchsticks []int) bool {
158
164
if s%4 != 0 {
159
165
return false
160
166
}
161
- sort.Ints ( matchsticks)
167
+ sort.Sort (sort. Reverse (sort. IntSlice ( matchsticks)) )
162
168
edges := make ([]int , 4 )
163
169
var dfs func (u, x int ) bool
164
170
dfs = func (u, x int ) bool {
165
- if u < 0 {
171
+ if u == len (matchsticks) {
166
172
return true
167
173
}
168
174
for i := 0 ; i < 4 ; i++ {
175
+ if i > 0 && edges[i-1 ] == edges[i] {
176
+ continue
177
+ }
169
178
edges[i] += matchsticks[u]
170
- if edges[i] <= x && dfs (u- 1 , x) {
179
+ if edges[i] <= x && dfs (u+ 1 , x) {
171
180
return true
172
181
}
173
182
edges[i] -= matchsticks[u]
174
183
}
175
184
return false
176
185
}
177
- return dfs (len (matchsticks)-1 , s/4 )
186
+ return dfs (0 , s/4 )
187
+ }
188
+ ```
189
+
190
+ ### ** Rust**
191
+
192
+ ``` rust
193
+ impl Solution {
194
+ pub fn makesquare (matchsticks : Vec <i32 >) -> bool {
195
+ let mut matchsticks = matchsticks ;
196
+
197
+ fn dfs (matchsticks : & Vec <i32 >, edges : & mut [i32 ; 4 ], u : usize , x : i32 ) -> bool {
198
+ if u == matchsticks . len () {
199
+ return true ;
200
+ }
201
+ for i in 0 .. 4 {
202
+ if i > 0 && edges [i - 1 ] == edges [i ] {
203
+ continue ;
204
+ }
205
+ edges [i ] += matchsticks [u ];
206
+ if edges [i ] <= x && dfs (matchsticks , edges , u + 1 , x ) {
207
+ return true ;
208
+ }
209
+ edges [i ] -= matchsticks [u ];
210
+ }
211
+ false
212
+ }
213
+
214
+ let sum : i32 = matchsticks . iter (). sum ();
215
+ if sum % 4 != 0 {
216
+ return false ;
217
+ }
218
+ matchsticks . sort_by (| x , y | y . cmp (x ));
219
+ let mut edges = [0 ; 4 ];
220
+
221
+ dfs (& matchsticks , & mut edges , 0 , sum / 4 )
222
+ }
178
223
}
179
224
```
180
225
0 commit comments