原题链接在这里:https://leetcode.com/problems/subsets-ii/
题目:
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note:
- Elements in a subset must be in non-descending order.
- The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2]
, a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
题解:
是Subsets的进阶版. 这里有duplicates, e.g. [1,2,2]但是res中不能包含两个[2].
还是backtracking, 注意去重.
Time Complexity: exponential.
Space: O(nums.length). stack space.
AC Java:
1 class Solution { 2 public List<List<Integer>> subsetsWithDup(int[] nums) { 3 List<List<Integer>> res = new ArrayList<List<Integer>>(); 4 Arrays.sort(nums); 5 dfs(nums, 0, new ArrayList<Integer>(), res); 6 return res; 7 } 8 9 private void dfs(int [] nums, int start, List<Integer> item, List<List<Integer>> res){ 10 res.add(new ArrayList<Integer>(item)); 11 for(int i = start; i<nums.length; i++){ 12 if(i>start && nums[i]==nums[i-1]){ 13 continue; 14 } 15 item.add(nums[i]); 16 dfs(nums, i+1, item, res); 17 item.remove(item.size()-1); 18 } 19 } 20 }
也所以在elem加完新元素想要放回res之前,需要先判断res中是否含有这个elem, 若是没有可以加到res中,若是已经有了,就不可以加到res中.
Time Complexity: exponential.
Space: O(res.size()).
AC Java:
1 public class Solution { 2 public List<List<Integer>> subsetsWithDup(int[] nums) { 3 List<List<Integer>> res = new ArrayList<List<Integer>>(); 4 if(nums == null || nums.length == 0){ 5 return res; 6 } 7 Arrays.sort(nums); 8 res.add(new ArrayList<Integer>()); 9 for(int i = 0; i<nums.length; i++){ 10 int size = res.size(); 11 for(int j = 0; j<size; j++){ 12 ArrayList<Integer> elem = new ArrayList<Integer>(res.get(j)); 13 elem.add(nums[i]); 14 if(!res.contains(elem)){ 15 res.add(elem); 16 } 17 } 18 } 19 return res; 20 } 21 }