Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: [1,2,2]
Output:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]
 
class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        result = new ArrayList<>();
        List<Integer> ans = new ArrayList<Integer>();
        Arrays.sort(nums); //nums可能是乱序的,要先排序
        backtrack(ans, nums, 0);
        return result;
    }
    
    public void backtrack(List<Integer> ans, int[] nums, int depth){
        if(depth >= nums.length) {
            List<Integer> new_ans = new ArrayList<Integer>(ans);
            result.add(new_ans);
            return;
        }
          
        int i = depth+1;
        while(i < nums.length){
            if(nums[depth] == nums[i]) i++;
            else break;
        }
        
        int j = depth;
        backtrack(ans, nums, i); //not add
        while(j < i){
            ans.add(nums[depth]);
            backtrack(ans, nums, i);
            j++;
        }
        
        //reset
        while(j > depth){
            ans.remove(ans.size()-1);
            j--;
        }  
    }
    
    private List<List<Integer>> result; 
}

 

相关文章:

  • 2021-07-19
  • 2021-06-21
  • 2022-03-07
  • 2021-11-27
  • 2021-11-22
  • 2021-05-28
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-27
  • 2021-07-03
相关资源
相似解决方案