##### Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/473.html

# 473. Matchsticks to Square (Medium)

Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.

Your input will be several matchsticks the girl has, represented with their stick length. Your output will either be true or false, to represent whether you could make one square using all the matchsticks the little match girl has.

Example 1:

Input: [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:

Input: [3,3,3,3,4]
Output: false

Explanation: You cannot find a way to form a square with all the matchsticks.


Note:

1. The length sum of the given matchsticks is in the range of 0 to 10^9.
2. The length of the given matchstick array will not exceed 15.

Related Topics:
Depth-first Search

## Solution 1. DP on Subsets

// OJ: https://leetcode.com/problems/matchsticks-to-square/
// Time: O(N * 2^N)
// Space: O(2^N)
class Solution {
vector<int> dp;
bool dfs(vector<int> &A, int used, int todo, int target) {
if (dp[used] != -1) return dp[used];
dp[used] = 0;
int mx = todo % target;
if (mx == 0) mx = target;
for (int i = 0; i < A.size() && !dp[used]; ++i) {
dp[used] = ((used >> i) & 1) == 0 && A[i] <= mx && dfs(A, used | (1 << i), todo - A[i], target);
}
return dp[used];
}
public:
bool makesquare(vector<int>& A) {
if (A.empty()) return false;
int len = accumulate(begin(A), end(A), 0);
if (len % 4 || *max_element(begin(A), end(A)) > len / 4) return false;
dp.assign(1 << A.size(), -1);
dp[(1 << A.size()) - 1] = 1;
return dfs(A, 0, len, len / 4);
}
};


## Solution 2. DFS to Fill Buckets

Let target = sum(A) / 4, which is the target length of each edge.

We use DFS to try to fill each A[i] into different edges.

Two optimizations here:

1. The unordered_set<int> seen is used to prevent handling the same edge value again. For example, assume edge = [1, 1, 1, 1], and now we are trying to add a stick of length 2 to it. Adding 2 to either 1 will yield the same result. So we just need to add to a edge with length 1 once.
2. Sorting the sticks in descending order will make it converge faster because it’s easy to fill in sands but hard to fill in peddles; filling peddles first will fail faster.
// OJ: https://leetcode.com/problems/matchsticks-to-square/
// Time: O(4^N)
// Space: O(N * SUM(A))
class Solution {
int edge[4] = {}, target;
bool dfs(vector<int> &A, int i) {
if (i == A.size()) return true;
unordered_set<int> seen;
for (int j = 0; j < 4; ++j) {
if (seen.count(edge[j]) || edge[j] + A[i] > target) continue;
seen.insert(edge[j]);
edge[j] += A[i];
if (dfs(A, i + 1)) return true;
edge[j] -= A[i];
}
return false;
}
public:
bool makesquare(vector<int>& A) {
if (A.size() < 4) return false;
int sum = accumulate(begin(A), end(A), 0);
if (sum % 4 || *max_element(begin(A), end(A)) > sum / 4) return false;
target = sum / 4;
sort(begin(A), end(A), greater<>());
return dfs(A, 0);
}
};

• class Solution {
public boolean makesquare(int[] nums) {
if (nums == null || nums.length < 4)
return false;
int sum = 0;
for (int num : nums)
sum += num;
if (sum % 4 != 0)
return false;
int sideLength = sum / 4;
boolean[] used = new boolean[nums.length];
return backtrack(nums, used, 0, 0, sideLength, 0);
}

public boolean backtrack(int[] nums, boolean[] used, int index, int sides, int sideLength, int curSideLength) {
if (sides == 4)
return true;
int length = nums.length;
boolean flag = false;
for (int i = index; i < length; i++) {
if (!used[i]) {
int num = nums[i];
int curSum = curSideLength + num;
if (curSum <= sideLength) {
used[i] = true;
if (curSum == sideLength)
flag = flag || backtrack(nums, used, 0, sides + 1, sideLength, 0);
else
flag = flag || backtrack(nums, used, i + 1, sides, sideLength, curSum);
if (flag)
break;
used[i] = false;
}
}
}
return flag;
}
}

############

class Solution {
public boolean makesquare(int[] matchsticks) {
int s = 0, mx = 0;
for (int v : matchsticks) {
s += v;
mx = Math.max(mx, v);
}
int x = s / 4, mod = s % 4;
if (mod != 0 || x < mx) {
return false;
}
Arrays.sort(matchsticks);
int[] edges = new int[4];
return dfs(matchsticks.length - 1, x, matchsticks, edges);
}

private boolean dfs(int u, int x, int[] matchsticks, int[] edges) {
if (u < 0) {
return true;
}
for (int i = 0; i < 4; ++i) {
if (i > 0 && edges[i - 1] == edges[i]) {
continue;
}
edges[i] += matchsticks[u];
if (edges[i] <= x && dfs(u - 1, x, matchsticks, edges)) {
return true;
}
edges[i] -= matchsticks[u];
}
return false;
}
}


• // OJ: https://leetcode.com/problems/matchsticks-to-square/
// Time: O(N * 2^N)
// Space: O(2^N)
class Solution {
public:
bool makesquare(vector<int>& A) {
int sum = accumulate(begin(A), end(A), 0), N = A.size();
if (sum % 4 || *max_element(begin(A), end(A)) > sum / 4) return false;
sum /= 4;
sort(begin(A), end(A), greater<>()); // Try rocks before sands
vector<int> dp(1 << N, -1); // -1 unvisited, 0 invalid, 1 valid
dp[(1 << N) - 1] = 1;
function<bool(int, int)> dfs = [&](int mask, int target) {
if (target == 0) target = sum;
for (int i = 0; i < N && !dp[mask]; ++i) {
if ((mask >> i & 1) || A[i] > target) continue;
}
};
return dfs(0, sum);
}
};

• class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
def dfs(u):
if u == len(matchsticks):
return True
for i in range(4):
if i > 0 and edges[i - 1] == edges[i]:
continue
edges[i] += matchsticks[u]
if edges[i] <= x and dfs(u + 1):
return True
edges[i] -= matchsticks[u]
return False

x, mod = divmod(sum(matchsticks), 4)
if mod or x < max(matchsticks):
return False
edges = [0] * 4
matchsticks.sort(reverse=True)
return dfs(0)

############

import collections

class Solution(object):
def makesquare(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums:
return False
sumLen = sum(nums)
if sumLen % 4 != 0:
return False
self.sideLen = sideLen = sumLen / 4
for side in nums:
if side > sideLen:
return False
halfLen = 2 * sideLen
sticksIdx = set([i for i in range(0, len(nums))])
nums.sort()

def backpack(nums, subset):
cands = [nums[k] for k in subset]
dp = [[False] * (self.sideLen + 1) for _ in range(len(cands))]
for i in range(0, len(cands)):
dp[i][0] = True
for i in range(0, len(cands)):
for j in range(1, self.sideLen + 1):
dp[i][j] |= dp[i - 1][j]
if j - cands[i] >= 0:
dp[i][j] |= dp[i - 1][j - cands[i]]
return dp[-1][-1]

def dfs(nums, start, sticksIdx, halfLen, subSum, subsetIdx):
if subSum >= halfLen:
if subSum == halfLen and backpack(nums, subsetIdx) and backpack(nums, sticksIdx):
return True
return False

for i in range(start, len(nums)):
if i > start and nums[i] == nums[i - 1]:
continue
if i in sticksIdx:
sticksIdx -= {i}
subsetIdx |= {i}
if dfs(nums, i + 1, sticksIdx, halfLen, subSum + nums[i], subsetIdx):
return True
subsetIdx -= {i}
sticksIdx |= {i}
return False

return dfs(nums, 0, sticksIdx, halfLen, 0, set())


• func makesquare(matchsticks []int) bool {
s := 0
for _, v := range matchsticks {
s += v
}
if s%4 != 0 {
return false
}
sort.Sort(sort.Reverse(sort.IntSlice(matchsticks)))
edges := make([]int, 4)
var dfs func(u, x int) bool
dfs = func(u, x int) bool {
if u == len(matchsticks) {
return true
}
for i := 0; i < 4; i++ {
if i > 0 && edges[i-1] == edges[i] {
continue
}
edges[i] += matchsticks[u]
if edges[i] <= x && dfs(u+1, x) {
return true
}
edges[i] -= matchsticks[u]
}
return false
}
return dfs(0, s/4)
}


• impl Solution {
pub fn makesquare(matchsticks: Vec<i32>) -> bool {
let mut matchsticks = matchsticks;

fn dfs(matchsticks: &Vec<i32>, edges: &mut [i32; 4], u: usize, x: i32) -> bool {
if u == matchsticks.len() {
return true;
}
for i in 0..4 {
if i > 0 && edges[i - 1] == edges[i] {
continue;
}
edges[i] += matchsticks[u];
if edges[i] <= x && dfs(matchsticks, edges, u + 1, x) {
return true;
}
edges[i] -= matchsticks[u];
}
false
}

let sum: i32 = matchsticks.iter().sum();
if sum % 4 != 0 {
return false;
}
matchsticks.sort_by(|x, y| y.cmp(x));
let mut edges = [0; 4];

dfs(&matchsticks, &mut edges, 0, sum / 4)
}
}