Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
求所有子集,要求求出所有結果大部分情況是用dfs進行搜索。參數中需要注意的是通過startIndex控制向前搜索,然後回溯法求解
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> results = new ArrayList<>();
// 邊界處理
if (nums == null) {
return results;
}
dfs(nums, 0, new ArrayList<>(), results);
return results;
}
private void dfs(int [] nums, int startIndex, List<Integer> subset, List<List<Integer>> results) {
//deepcopy subset to results
results.add(new ArrayList<>(subset));
//dfs 回溯求subsets
for (int i = startIndex; i < nums.length; i++) {
subset.add(nums[i]);
dfs(nums, i + 1, subset, results);
subset.remove(subset.size() - 1);
}
}
}
90.Subsets II
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Input: [1,2,2]
Output:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
Subsets II和Subsets的區別是輸入中可以存在重複元素,1和第一個2 ,1和第二個2是相同的,選擇一個。所以要在Subsets 的基礎上進行選代表操作,不能跳過第一個2選擇第二個2,要添加的操作是如果後一個數等於前一個數且沒有選擇前一個數擇跳過,對應代碼爲
if (i != 0 && nums[i] == nums[i - 1] && i > startIndex) {
continue;
}
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> results = new ArrayList<>();
if (nums == null) {
return results;
}
Arrays.sort(nums);
dfs(nums, 0, new ArrayList<Integer>(), results);
return results;
}
private void dfs(int [] nums, int startIndex, List<Integer> subset, List<List<Integer>> results) {
results.add(new ArrayList<>(subset));
for (int i = startIndex; i < nums.length; i++) {
//如果當前數和前一位相同且沒有選前一位 continue
if (i != 0 && nums[i] == nums[i - 1] && i > startIndex) {
continue;
}
subset.add(nums[i]);
dfs(nums, i + 1, subset, results);
subset.remove(subset.size() - 1);
}
}
}