# Subsets I & II

lpy1990

## Subsets I

Given a set of distinct integers, nums, return all possible subsets
(the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3],
[1,3], [2,3], [1,2], [] ]

### 代码

``````class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length == 0) {
return res;
}
List<Integer> tmp = new ArrayList<>();
dfs(nums, tmp, res, 0);
return res;
}
private void dfs(int[] nums, List<Integer> tmp, List<List<Integer>> res, int index) {
for (int i = index; i <nums.length; i++) {
dfs(nums, tmp, res, i +1);
tmp.remove(tmp.size() -1);
}
}
}``````

## Subsets II

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],
[] ]

### 代码

``````class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length == 0) {
return res;
}
Arrays.sort(nums);
List<Integer> tmp = new ArrayList<>();
dfs(nums, tmp, res, 0);
return res;
}
private void dfs(int[] nums, List<Integer> tmp, List<List<Integer>> res, int index) {
for (int i = index; i <nums.length; i++) {
if (i != index && nums[i] == nums[i-1]) {
continue;
}