-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0473_matchsticks_to_square.go
More file actions
43 lines (38 loc) · 984 Bytes
/
s0473_matchsticks_to_square.go
File metadata and controls
43 lines (38 loc) · 984 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
https://leetcode.com/problems/matchsticks-to-square/
You are given an integer array matchsticks where matchsticks[i] is the length
of
the ith matchstick. You want to use all the matchsticks to make one square.
You should not break any stick, but you can link them up, and each matchstick
must be used exactly one time.
Return true if you can make this square and false otherwise.
*/
package solutions
import "sort"
func makesquare(matchsticks []int) bool {
sum := Sum(matchsticks...)
if sum%4 != 0 {
return false
}
sideLen, sides := sum/4, make([]int, 4)
sort.Slice(matchsticks, func(i, j int) bool {
return matchsticks[i] > matchsticks[j]
})
var bt func(i int) bool
bt = func(i int) bool {
if i == len(matchsticks) {
return true
}
for j := 0; j < 4; j++ {
if sides[j]+matchsticks[i] <= sideLen {
sides[j] += matchsticks[i]
if bt(i + 1) {
return true
}
sides[j] -= matchsticks[i]
}
}
return false
}
return bt(0)
}