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], [] ]
与subset I差不多,只需加上判断集合是否已经在st中存在即可,判断if(!st.contains(a)) 后再添加。注意,[]空集要在最后添加,否则每个集合在判断contains时都默认已经添加进去了。
Source
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] num) {
List<List<Integer>> st = new ArrayList<List<Integer>>();
List<Integer> a = new ArrayList<Integer>();
if(num.length == 0){
st.add(a);
return st;
}
Arrays.sort(num);
int start = 0;
boolean[] visited = new boolean[num.length + 1];
for(int len = 1; len <= num.length; len++)
searchNum(start, len, num, st, a, visited);
st.add(new ArrayList<Integer>(a));
return st;
}
public void searchNum(int start, int len, int[] S, List<List<Integer>> st, List<Integer> a, boolean[] visited){
if(a.size() == len){
if(!st.contains(a))
st.add(new ArrayList<Integer>(a)); //注意递归时的st添加要为a新分配空间
return;
}
for(int i = start; i < S.length; i++){
if(!visited[i]){
a.add(S[i]);
visited[i] = true;
searchNum(i, len, S, st, a, visited);
a.remove(a.size() - 1); //remove***
visited[i] = false;
}
}
}
}
Test
public static void main(String[] args){
int[] S = {1,2,2};
System.out.println(new Solution().subsetsWithDup(S));
}