27
27
*/
28
28
public class _473 {
29
29
30
- /**Partially inspired by: https://discuss.leetcode.com/topic/72107/java-dfs-solution-with-explanation/2*/
31
-
32
- /**One hidden requirement: you'll have to use up all of the given matchsticks, nothing could be left behind.*/
30
+ 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
+ */
33
35
public boolean makesquare (int [] nums ) {
34
36
if (nums == null || nums .length < 4 ) {
35
37
return false ;
@@ -47,35 +49,36 @@ public boolean makesquare(int[] nums) {
47
49
return dfs (nums , new int [4 ], 0 , sum / 4 );
48
50
}
49
51
50
- private boolean dfs (int [] nums , int [] sums , int index , int target ) {
51
- if (index == nums .length ) {
52
- if (sums [0 ] == target && sums [1 ] == target && sums [2 ] == target ) {
53
- return true ;
54
- }
55
- return false ;
56
- }
57
- for (int i = 0 ; i < 4 ; i ++) {
58
- if (sums [i ] + nums [index ] > target ) {
59
- continue ;
52
+ private boolean dfs (int [] nums , int [] sums , int index , int target ) {
53
+ if (index == nums .length ) {
54
+ if (sums [0 ] == target && sums [1 ] == target && sums [2 ] == target ) {
55
+ return true ;
56
+ }
57
+ return false ;
60
58
}
61
- sums [i ] += nums [index ];
62
- if (dfs (nums , sums , index + 1 , target )) {
63
- return true ;
59
+ for (int i = 0 ; i < 4 ; i ++) {
60
+ if (sums [i ] + nums [index ] > target ) {
61
+ continue ;
62
+ }
63
+ sums [i ] += nums [index ];
64
+ if (dfs (nums , sums , index + 1 , target )) {
65
+ return true ;
66
+ }
67
+ sums [i ] -= nums [index ];
64
68
}
65
- sums [ i ] -= nums [ index ] ;
69
+ return false ;
66
70
}
67
- return false ;
68
- }
69
71
70
- private void reverse (int [] nums ) {
71
- int left = 0 ;
72
- int right = nums .length - 1 ;
73
- while (left < right ) {
74
- int tmp = nums [left ];
75
- nums [left ] = nums [right ];
76
- nums [right ] = tmp ;
77
- left ++;
78
- right --;
72
+ private void reverse (int [] nums ) {
73
+ int left = 0 ;
74
+ int right = nums .length - 1 ;
75
+ while (left < right ) {
76
+ int tmp = nums [left ];
77
+ nums [left ] = nums [right ];
78
+ nums [right ] = tmp ;
79
+ left ++;
80
+ right --;
81
+ }
79
82
}
80
83
}
81
84
0 commit comments