|
2 | 2 |
|
3 | 3 | import java.util.Arrays;
|
4 | 4 |
|
5 |
| -/** |
6 |
| - * 473. Matchsticks to Square |
7 |
| - * |
8 |
| - * Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, |
9 |
| - * please find out a way you can make one square by using up all those matchsticks. |
10 |
| - * You should not break any stick, but you can link them up, and each matchstick must be used exactly one time. |
11 |
| - * Your input will be several matchsticks the girl has, represented with their stick length. |
12 |
| - * 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. |
13 |
| -
|
14 |
| - Example 1: |
15 |
| - Input: [1,1,2,2,2] |
16 |
| - Output: true |
17 |
| - Explanation: You can form a square with length 2, one side of the square came two sticks with length 1. |
18 |
| -
|
19 |
| - Example 2: |
20 |
| - Input: [3,3,3,3,4] |
21 |
| - Output: false |
22 |
| - Explanation: You cannot find a way to form a square with all the matchsticks. |
23 |
| -
|
24 |
| - Note: |
25 |
| - The length sum of the given matchsticks is in the range of 0 to 10^9. |
26 |
| - The length of the given matchstick array will not exceed 15. |
27 |
| - */ |
28 | 5 | public class _473 {
|
29 | 6 |
|
30 | 7 | public static class Solution1 {
|
31 |
| - /** |
32 |
| - * Partially inspired by: https://discuss.leetcode.com/topic/72107/java-dfs-solution-with-explanation/2 |
33 |
| - * One hidden requirement: you'll have to use up all of the given matchsticks, nothing could be left behind. |
34 |
| - */ |
35 |
| - public boolean makesquare(int[] nums) { |
36 |
| - if (nums == null || nums.length < 4) { |
37 |
| - return false; |
38 |
| - } |
39 |
| - Arrays.sort(nums); |
40 |
| - reverse(nums); |
41 |
| - int sum = 0; |
42 |
| - for (int i : nums) { |
43 |
| - sum += i; |
44 |
| - } |
45 |
| - if (sum % 4 != 0) { |
46 |
| - return false; |
47 |
| - } |
| 8 | + /** |
| 9 | + * Partially inspired by: https://discuss.leetcode.com/topic/72107/java-dfs-solution-with-explanation/2 |
| 10 | + * One hidden requirement: you'll have to use up all of the given matchsticks, nothing could be left behind. |
| 11 | + */ |
| 12 | + public boolean makesquare(int[] nums) { |
| 13 | + if (nums == null || nums.length < 4) { |
| 14 | + return false; |
| 15 | + } |
| 16 | + Arrays.sort(nums); |
| 17 | + reverse(nums); |
| 18 | + int sum = 0; |
| 19 | + for (int i : nums) { |
| 20 | + sum += i; |
| 21 | + } |
| 22 | + if (sum % 4 != 0) { |
| 23 | + return false; |
| 24 | + } |
48 | 25 |
|
49 |
| - return dfs(nums, new int[4], 0, sum / 4); |
50 |
| - } |
| 26 | + return dfs(nums, new int[4], 0, sum / 4); |
| 27 | + } |
51 | 28 |
|
52 | 29 | private boolean dfs(int[] nums, int[] sums, int index, int target) {
|
53 | 30 | if (index == nums.length) {
|
|
0 commit comments