8
8
public class Subsets {
9
9
10
10
public static void main (String ...strings ){
11
- int [] nums = new int []{1 ,2 ,3 };
12
- List <List <Integer >> result = subsets (nums );
11
+ // int[] nums = new int[]{1,2,3};
12
+ int [] nums = new int []{1 ,2 ,2 };
13
+ List <List <Integer >> result = subsets_backtracking (nums );
13
14
CommonUtils .printIntegerList (result );
14
15
}
15
16
@@ -29,5 +30,23 @@ public static List<List<Integer>> subsets(int[] nums) {
29
30
}
30
31
return result ;
31
32
}
33
+
34
+ /**this post: https://discuss.leetcode.com/topic/46159/a-general-approach-to-backtracking-questions-in-java-subsets-permutations-combination-sum-palindrome-partitioning
35
+ * is really cool!*/
36
+ public static List <List <Integer >> subsets_backtracking (int [] nums ) {
37
+ List <List <Integer >> result = new ArrayList ();
38
+ backtracking (result , new ArrayList <>(), nums , 0 );
39
+ return result ;
40
+ }
32
41
42
+ private static void backtracking (List <List <Integer >> result , List <Integer > temp , int [] nums , int start ) {
43
+ //ATTN: you'll have to make a new list here before entering the for loop
44
+ result .add (new ArrayList (temp ));
45
+ for (int i = start ; i < nums .length ; i ++){
46
+ if (i != start && nums [i ] == nums [i -1 ]) continue ;//add this line here to skip duplicates for Subsets II
47
+ temp .add (nums [i ]);
48
+ backtracking (result , temp , nums , i +1 );
49
+ temp .remove (temp .size ()-1 );
50
+ }
51
+ }
33
52
}
0 commit comments