Skip to content

Commit c5d2cae

Browse files
authored
Create SubsetsII.java
1 parent da5aef3 commit c5d2cae

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Backtracking/SubsetsII.java

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
//LeetCode 90. Subsets II
2+
//Question - https://leetcode.com/problems/subsets-ii/
3+
4+
class Solution {
5+
public List<List<Integer>> subsetsWithDup(int[] nums) {
6+
List<List<Integer>> res = new ArrayList<>();
7+
8+
//By sorting the array duplicates would come together consecutively
9+
Arrays.sort(nums);
10+
11+
helper(nums, 0, new ArrayList<>(), res);
12+
return res;
13+
}
14+
15+
public void helper(int nums[], int index, List<Integer> subset, List<List<Integer>> res){
16+
res.add(new ArrayList<>(subset));
17+
18+
for(int i = index ; i < nums.length ; i++){
19+
//Always include the first distinct number and ignore the following duplicates
20+
if(i > index && nums[i] == nums[i-1]) continue;
21+
22+
subset.add(nums[i]);
23+
helper(nums, i+1, subset, res);
24+
subset.remove(subset.size()-1);
25+
26+
}
27+
}
28+
}

0 commit comments

Comments
 (0)