78. Subsets
https://leetcode.com/problems/subsets/
这两道取子集的题目基本上也没什么好讲的,基本的回溯方法即可,处理方式同排列和组合系列。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public List<List<Integer>> subsets(int[] nums) { if (nums == null || nums.length == 0) { return new ArrayList<>(); } List<List<Integer>> result = new ArrayList<>(); handle(nums, 0, new ArrayList<>(), result); return result; }
private void handle(int[] nums, int start, List<Integer> cur, List<List<Integer>> result) { result.add(new ArrayList<>(cur)); for (int i = start; i < nums.length; i++) { cur.add(nums[i]); handle(nums, i + 1, cur, result); cur.remove(cur.size() - 1); } }
|
90. Subsets II
https://leetcode.com/problems/subsets-ii/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public List<List<Integer>> subsetsWithDup(int[] nums) { if (nums == null || nums.length == 0) { return new ArrayList<>(); } List<List<Integer>> result = new ArrayList<>(); Arrays.sort(nums); handle(nums, 0, new ArrayList<>(), result); return result; }
private void handle(int[] nums, int start, List<Integer> cur, List<List<Integer>> result) { result.add(new ArrayList<>(cur)); for (int i = start; i < nums.length; i++) { if (i > start && nums[i] == nums[i - 1]) { continue; } cur.add(nums[i]); handle(nums, i + 1, cur, result); cur.remove(cur.size() - 1); } }
|