1 public class Solution { 2 public List<List<Integer>> subsetsWithDup(int[] nums) { 3 Arrays.sort(nums); 4 List<List<Integer>> subsets = new ArrayList<>(); 5 List<Integer> tempSubset = new ArrayList<>(); 6 boolean[] hasVisited = new boolean[nums.length]; 7 for (int size = 0; size <= nums.length; size++) { 8 backtracking(0, tempSubset, subsets, hasVisited, size, nums); // 不同的子集大小 9 } 10 return subsets; 11 } 12 13 private void backtracking(int start, List<Integer> tempSubset, List<List<Integer>> subsets, boolean[] hasVisited, 14 final int size, final int[] nums) { 15 16 if (tempSubset.size() == size) { 17 subsets.add(new ArrayList<>(tempSubset)); 18 return; 19 } 20 for (int i = start; i < nums.length; i++) { 21 if (i != 0 && nums[i] == nums[i - 1] && !hasVisited[i - 1]) { 22 continue; 23 } 24 tempSubset.add(nums[i]); 25 hasVisited[i] = true; 26 backtracking(i + 1, tempSubset, subsets, hasVisited, size, nums); 27 hasVisited[i] = false; 28 tempSubset.remove(tempSubset.size() - 1); 29 } 30 } 31 }
对比leetcode78:
1 public class Solution { 2 public List<List<Integer>> subsets(int[] nums) { 3 List<List<Integer>> subsets = new ArrayList<>(); 4 List<Integer> tempSubset = new ArrayList<>(); 5 for (int size = 0; size <= nums.length; size++) { 6 backtracking(0, tempSubset, subsets, size, nums); // 不同的子集大小 7 } 8 return subsets; 9 } 10 11 private void backtracking(int start, List<Integer> tempSubset, List<List<Integer>> subsets, 12 final int size, final int[] nums) { 13 14 if (tempSubset.size() == size) { 15 subsets.add(new ArrayList<>(tempSubset)); 16 return; 17 } 18 for (int i = start; i < nums.length; i++) { 19 tempSubset.add(nums[i]); 20 backtracking(i + 1, tempSubset, subsets, size, nums); 21 tempSubset.remove(tempSubset.size() - 1); 22 } 23 } 24 }