Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note: 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],
[]
]
Solution:Backtracking
思路:
总结见:http://www.jianshu.com/p/883fdda93a66
其实就是backtracking 的 simple组合问题 + 去重,套路ok,没有终止条件,每一步都add到cur_res.
Time Complexity: O(2^n) Space Complexity: O(2N) 不算result, 含递归缓存和cur_res
Solution Code:
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> cur_res = new ArrayList<>();
Arrays.sort(nums);
backtrack(nums, 0, cur_res, result);
return result;
}
private void backtrack(int [] nums, int start, List<Integer> cur_res, List<List<Integer>> result) {
result.add(new ArrayList<>(cur_res));
for(int i = start; i < nums.length; i++){
if(i > start && nums[i] == nums[i - 1]) continue; // skip duplicates
cur_res.add(nums[i]);
backtrack(nums, i + 1, cur_res, result);
cur_res.remove(cur_res.size() - 1);
}
}
}