90. Subsets II

/*

90. Subsets II
My Submissions
Question
Editorial Solution
Total Accepted: **69575** Total Submissions: **224792** Difficulty: **Medium**

Given a collection of integers that might contain duplicates, ***nums***, return all possible subsets.
**Note:** The solution set must not contain duplicate subsets.
For example,
If ***nums*** = [1,2,2], a solution is:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

Hide Company Tags Facebook
Hide Tags Array Backtracking
*/
public class Solution {
    public List> subsetsWithDup(int[] nums) {
        //https://leetcode.com/discuss/54544/very-simple-and-fast-java-solution
        /*
        The Basic idea is: use "while (i < n.length && n[i] == n[i - 1]) {i++;}" to avoid the duplicate. For example, the input is 2 2 2 3 4. Consider the helper function. The process is:

each.add(n[i]); --> add first 2 (index 0)
helper(res, new ArrayList<>(each), i + 1, n); --> go to recursion part, list each is <2 (index 0)>
while (i < n.length && n[i] == n[i - 1]) {i++;} --> after this, i == 3, add the element as in subset I
        */
        Arrays.sort(nums);
        List> res = new ArrayList<>();
        List cur = new ArrayList<>();
        
        helper(res, cur, 0, nums);
        return res;
        
    }
    

    public void helper(List> res, List cur, int pos, int[] n) {
        if (pos <= n.length) {
            res.add(cur);
        }
        
        int i = pos;
        while (i < n.length) {
            cur.add(n[i]);
            helper(res, new ArrayList<>(cur), i+1, n);
            cur.remove(cur.size() - 1);
            i++;
            while( i < n.length &&  n[i] == n[i-1]) {
                i++;
            }
        }
        return;
    }
}

你可能感兴趣的:(90. Subsets II)