90. Subsets II

2020/01/10 Leetcode

90. Subsets II

Tags: ‘Array’, ‘Backtracking’

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: [1,2,2]
Output:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

Solution

用backtrack模板,注意termination, 剪枝trimming 98% 100% ```java public List<List> subsetsWithDup(int[] nums) { List<List> result = new ArrayList<>(); Arrays.sort(nums); backtrack(result, new ArrayList(), nums, 0); return result; }

private void backtrack(List<List<Integer>> result, List<Integer> temp, int[] nums, int start) {
    result.add(new ArrayList<>(temp)); // 没有termination,需要所有subset
    for(int i = start; i < nums.length; i++) {
        if (i > start && nums[i] == nums[i-1]) {
            continue; // skip duplicates
        }
        
        temp.add(nums[i]);
        backtrack(result, temp, nums, i+1);
        temp.remove(temp.size() - 1);
    }
}
```

Search

    Table of Contents