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],
[]
]
代碼:
public List<List<Integer>> subsets(int[] nums) {
if (nums == null) {
return null;
}
List<List<Integer>> res = new ArrayList<>();
ArrayList<Integer> emptyList = new ArrayList<>();
res.add(emptyList);
for(int i = 0; i < nums.length; i++) {
int size = res.size();
for(int j = 0; j < size; j++) {
ArrayList<Integer> newList = new ArrayList<Integer>(res.get(j));
newList.add(nums[i]);
res.add(newList);
}
}
return res;
}
Follow Up: 90. 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],
[]
]
Solution:
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null) {
return res;
}
Arrays.sort(nums);
ArrayList<Integer> emptyList = new ArrayList<>();
res.add(emptyList);
int sameCount = 1;
for(int i = 0; i < nums.length; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
sameCount++;
} else {
sameCount = 1;
}
int size = res.size();
int start = size - size / sameCount;
for (int j = start; j < size; j++) {
ArrayList<Integer> newList = new ArrayList<Integer>(res.get(j));
newList.add(nums[i]);
res.add(newList);
}
}
return res;
}