78.子集
操作元素不重复
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> subsets(int[] nums) {
helper(nums, 0);
return result;
}
public void helper(int[] nums, int startIndex){
result.add(new ArrayList<>(path));
for(int i = startIndex; i < nums.length; i++){
path.add(nums[i]);
helper(nums, i + 1);
path.removeLast();
}
}
}
90.子集II
操作元素可能包含重复元素
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
helper(nums, 0);
return result;
}
public void helper(int[] nums, int startIndex){
result.add(new ArrayList<>(path));
for(int i = startIndex; i < nums.length; i++){
//层级去重
if(i > startIndex && nums[i - 1] == nums[i]) continue;
path.add(nums[i]);
helper(nums, i + 1);
path.removeLast();
}
}
}