Skip to content

Commit 76b7d81

Browse files
committed
Solution as on 12-07-2022 10:20 pm
1 parent e891d08 commit 76b7d81

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

0473. Matchsticks to Square.cpp

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// 473.✅ Matchsticks to Square
2+
3+
class Solution
4+
{
5+
public:
6+
bool helper(vector<int> &matchsticks, int target, vector<int> &sides, int idx)
7+
{
8+
if (idx == matchsticks.size())
9+
{
10+
if (sides[0] == sides[1] && sides[1] == sides[2] && sides[2] == sides[3])
11+
return true;
12+
return false;
13+
}
14+
15+
for (int i = 0; i < 4; ++i)
16+
{
17+
if (sides[i] + matchsticks[idx] > target)
18+
continue;
19+
int j = i - 1;
20+
while (j >= 0)
21+
{
22+
if (sides[i] == sides[j])
23+
break;
24+
--j;
25+
}
26+
if (j != -1)
27+
continue;
28+
sides[i] += matchsticks[idx];
29+
if (helper(matchsticks, target, sides, idx + 1))
30+
return true;
31+
sides[i] -= matchsticks[idx];
32+
}
33+
return false;
34+
}
35+
36+
bool makesquare(vector<int> &matchsticks)
37+
{
38+
if (matchsticks.size() == 0)
39+
return false;
40+
int sum = 0;
41+
sum = accumulate(matchsticks.begin(), matchsticks.end(), 0);
42+
vector<int> sides(4, 0);
43+
sort(matchsticks.begin(), matchsticks.end(), greater<int>());
44+
return helper(matchsticks, sum / 4, sides, 0);
45+
}
46+
};

0 commit comments

Comments
 (0)