Subsets II 原题地址:
https://oj.leetcode.com/problems/subsets-ii/
Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
- Elements in a subset must be in non-descending order.
- The solution set must not contain duplicate subsets.
For example,
If S = [1,2,2]
, a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]S中有重复元素,那么就要避免S'+第一个2,和S'+第二个2相同的情况(S'∈S),那么维护一个boolean数组,表示某一元素是否被选中,当前一个元素和当前元素相同,而且前一个元素没有被选中的情况下,那么这个元素就不去选他,就可以避免这种情况。
public class Solution {
private List<List<Integer>> ans = new LinkedList<List<Integer>>();
public List<List<Integer>> subsetsWithDup(int[] S) {
if (S == null || S.length == 0)
return ans;
LinkedList<Integer> temp = new LinkedList<Integer>();
Arrays.sort(S);
int[] flag = new int[S.length];
search(temp, S, 0, flag);
return ans;
}
private void search(LinkedList<Integer> temp, int[] S, int idx, int[] flag) {
if (idx == S.length) {
LinkedList<Integer> list = (LinkedList<Integer>) temp.clone();
ans.add(list);
return;
}
if (idx == 0 || S[idx] != S[idx-1] || (S[idx] == S[idx-1] && flag[idx-1] == 1)) {
temp.add(S[idx]);
flag[idx] = 1;
search(temp, S, idx+1, flag);
flag[idx] = 0;
temp.pollLast();
}
search(temp, S, idx+1, flag);
}
}