image.png

解决思路

回溯+剪枝

  1. class Solution {
  2. public List<List<Integer>> subsetsWithDup(int[] nums) {
  3. List<List<Integer>> res = new ArrayList<>();
  4. if (nums == null || nums.length == 0)
  5. return res;
  6. //先排序
  7. Arrays.sort(nums);
  8. backtrack(0,nums,res,new ArrayDeque<>());
  9. return res;
  10. }
  11. private void backtrack(int begin,int[] nums,List<List<Integer>> res,Deque<Integer> temp){
  12. res.add(new ArrayList<>(temp));
  13. for (int i = begin;i < nums.length;i++){
  14. //剪枝
  15. if (i > begin && nums[i] == nums[i - 1])
  16. continue;
  17. temp.addLast(nums[i]);
  18. backtrack(i + 1,nums,res,temp);
  19. temp.removeLast();
  20. }
  21. }
  22. }