473. Matchsticks to Square
Problem
Tags: Array
, Dynamic Programming
, Backtracking
, Bit Manipulation
, Bitmask
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:
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:
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
Code
JS
// 473. Matchsticks to Square (2/2/53427)
// Runtime: 84 ms (79.85%) Memory: 39.19 MB (94.57%)
/**
* @param {number[]} matchsticks
* @return {boolean}
*/
var makesquare = function(matchsticks) {
const n = matchsticks.length;
const sum = matchsticks.reduce((a, b) => a + b, 0);
if (sum % 4 != 0) return false;
matchsticks.sort((a, b) => a - b);
return dfs(matchsticks, new Array(4).fill(0), matchsticks.length - 1, sum / 4);
};
var dfs = function (nums, sums, index, target) {
if (index == -1) return true;
for (let i = 0; i < 4; i++) {
if (sums[i] + nums[index] > target || (i > 0 && sums[i] == sums[i - 1])) continue;
sums[i] += nums[index];
if (dfs(nums, sums, index - 1, target)) return true;
sums[i] -= nums[index];
}
return false;
};