473 Matchsticks to Square

1. Question

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:
1
Input: [1,1,2,2,2]
2
3
Output: true
4
5
Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.
Copied!
Example 2:
1
Input: [3,3,3,3,4]
2
3
Output: false
4
5
Explanation: You cannot find a way to form a square with all the matchsticks.
Copied!
Note:
  1. 1.
    The length sum of the given matchsticks is in the range of0to10^9.
  2. 2.
    The length of the given matchstick array will not exceed15.

2. Implementation

(1) Backtracking
1
class Solution {
2
public boolean makesquare(int[] nums) {
3
if (nums == null || nums.length == 0) {
4
return false;
5
}
6
7
int sum = 0;
8
for (int num : nums) {
9
sum += num;
10
}
11
12
if (sum % 4 != 0) {
13
return false;
14
}
15
16
Arrays.sort(nums);
17
reverse(nums);
18
int[] squareEdge = new int[4];
19
return recMakeSquare(0, squareEdge, nums, sum / 4);
20
}
21
22
public boolean recMakeSquare(int index, int[] squareEdge, int[] nums, int target) {
23
if (index == nums.length) {
24
return squareEdge[0] == squareEdge[1] && squareEdge[1] == squareEdge[2];
25
}
26
27
for (int i = 0; i < 4; i++) {
28
if (squareEdge[i] + nums[index] > target) {
29
continue;
30
}
31
32
squareEdge[i] += nums[index];
33
if (recMakeSquare(index + 1, squareEdge, nums, target)) {
34
return true;
35
}
36
squareEdge[i] -= nums[index];
37
}
38
return false;
39
}
40
41
public void reverse(int[] nums) {
42
for (int i = 0; i < nums.length / 2; i++) {
43
int temp = nums[i];
44
nums[i] = nums[nums.length - 1 - i];
45
nums[nums.length - 1 - i] = temp;
46
}
47
}
48
}
Copied!

3. Time & Space Complexity

Backtracking: 时间复杂度O(n!) 解析, 空间复杂度O(n)