2424
2525public class _78 {
2626
27- public static class IterativeSolution {
28-
27+ public static class Solution1 {
2928 public static List <List <Integer >> subsets (int [] nums ) {
3029 List <List <Integer >> result = new ArrayList ();
31- List <Integer > empty = new ArrayList ();
32- result .add (empty );
3330 if (nums == null ) {
3431 return result ;
3532 }
33+ result .add (new ArrayList ());
3634 for (int i = 0 ; i < nums .length ; i ++) {
3735 List <List <Integer >> temp = new ArrayList ();
3836 //you'll have to create a new one here, otherwise, it'll throw ConcurrentModificationException.
@@ -45,25 +43,44 @@ public static List<List<Integer>> subsets(int[] nums) {
4543 }
4644 return result ;
4745 }
48-
4946 }
5047
51- public static class BacktrackingSolution {
52-
48+ public static class Solution2 {
5349 public List <List <Integer >> subsets (int [] nums ) {
5450 List <List <Integer >> result = new ArrayList ();
5551 backtracking (result , new ArrayList (), nums , 0 );
5652 return result ;
5753 }
5854
59- void backtracking (List <List <Integer >> result , List <Integer > temp , int [] nums , int start ) {
60- result .add (new ArrayList (temp ));
55+ void backtracking (List <List <Integer >> result , List <Integer > list , int [] nums , int start ) {
56+ result .add (new ArrayList (list ));
6157 for (int i = start ; i < nums .length ; i ++) {
62- temp .add (nums [i ]);
63- backtracking (result , temp , nums , i + 1 );
64- temp .remove (temp .size () - 1 );
58+ list .add (nums [i ]);
59+ backtracking (result , list , nums , i + 1 );
60+ list .remove (list .size () - 1 );
6561 }
6662 }
63+ }
6764
65+ public static class Solution3 {
66+ /**
67+ * This is just a slight modification of Solution2, pay close to attention to notice the difference between them.
68+ */
69+ public List <List <Integer >> subsets (int [] nums ) {
70+ List <List <Integer >> result = new ArrayList <>();
71+ List <Integer > list = new ArrayList <>();
72+ result .add (list );
73+ backtracking (result , list , nums , 0 );
74+ return result ;
75+ }
76+
77+ private void backtracking (List <List <Integer >> result , List <Integer > list , int [] nums , int start ) {
78+ for (int i = start ; i < nums .length ; i ++) {
79+ list .add (nums [i ]);
80+ result .add (new ArrayList <>(list ));
81+ backtracking (result , list , nums , i + 1 );
82+ list .remove (list .size () - 1 );
83+ }
84+ }
6885 }
6986}
0 commit comments