Skip to content

Commit 47eea51

Browse files
use backtracking to solve Subsets I & II
1 parent f2c3511 commit 47eea51

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

MEDIUM/src/medium/Subsets.java

+21-2
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,9 @@
88
public class Subsets {
99

1010
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);
1314
CommonUtils.printIntegerList(result);
1415
}
1516

@@ -29,5 +30,23 @@ public static List<List<Integer>> subsets(int[] nums) {
2930
}
3031
return result;
3132
}
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+
}
3241

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+
}
3352
}

0 commit comments

Comments
 (0)