ID | Title | Difficulty | |
---|---|---|---|
Loading... |
473. Matchsticks to Square
Medium
LeetCode
Array, Dynamic Programming, Backtracking, Bit Manipulation, Bitmask
Problem
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.
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
class Solution {
public boolean makesquare(int[] matchsticks) {
int sum = 0;
for(int num : matchsticks){
sum += num;
}
if(sum % 4 != 0) return false;
sum /= 4;
// [1,1,1,1,1,1,1,1,1,1,1,1,1,1,102]
Arrays.sort(matchsticks);
reverse(matchsticks);
return dfs(matchsticks, new int[4], 0, sum);
}
private boolean dfs(int[] nums, int[] sums, int index, int sum){
if(index == nums.length){
if(sums[0] == sum && sums[1] == sum && sums[2] == sum){
return true;
}
return false;
}
int num = nums[index];
for(int i = 0; i < 4; i++){
if(sums[i] + num > sum) continue;
sums[i] += num;
if(dfs(nums, sums, index + 1, sum)) return true;
sums[i] -= num;
}
return false;
}
private void reverse(int[] nums) {
int i = 0;
int j = nums.length - 1;
while (i < j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
i++;
j--;
}
}
}
按 <- 键看上一题!
470. Implement Rand10() Using Rand7()
按 -> 键看下一题!
474. Ones and Zeroes