473. Matchsticks to Square

473. Matchsticks to Square

Description

You are given an integer array matchsticks where matchsticks[i] is the length of the i^th 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.

Example 1:

1
2
3
Input: matchsticks = [1,1,2,2,2]
Output: true
Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.

Example 2:

1
2
3
Input: matchsticks = [3,3,3,3,4]
Output: false
Explanation: You cannot find a way to form a square with all the matchsticks.

Constraints:

  • 1 <= matchsticks.length <= 15
  • 1 <= matchsticks[i] <= 10^8

Hints/Notes

Solution

Language: C++

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
class Solution {
public:
bool makesquare(vector<int>& matchsticks) {
int sum = reduce(matchsticks.begin(), matchsticks.end());
if (sum % 4) {
return false;
}
int side = sum / 4;
if (ranges::max(matchsticks) > side) {
return false;
}
sort(matchsticks.begin(), matchsticks.end(), greater<int>());
vector<int> sticks(4, 0);
return dfs(0, matchsticks, sticks, side);
}

bool dfs(int idx, vector<int>& matchsticks, vector<int>& sticks, const int side) {
if (idx == matchsticks.size()) {
return true;
}
bool res = false;
for (int i = 0; i < sticks.size(); i++) {
if (sticks[i] + matchsticks[idx] > side) {
continue;
}
sticks[i] += matchsticks[idx];
res |= dfs(idx + 1, matchsticks, sticks, side);
sticks[i] -= matchsticks[idx];
if (res) {
return true;
}
}
return false;
}
};