LeetCode 61 Subsets II
1359 ワード
Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
1, Elements in a subset must be in non-descending order.
2, The solution set must not contain duplicate subsets.
For example,
If S = [1,2,2], a solution is:
return allを見てまずdfsが解決できるかどうかを考えます.
num配列を並べ替えると、同じ要素が隣接し、重複を判断できます.
配列を巡り、各要素をitemに加え、後ろの部分を再帰的に検索します.
Note:
1, Elements in a subset must be in non-descending order.
2, 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],
[]
]
分析:return allを見てまずdfsが解決できるかどうかを考えます.
num配列を並べ替えると、同じ要素が隣接し、重複を判断できます.
配列を巡り、各要素をitemに加え、後ろの部分を再帰的に検索します.
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] num) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> item = new ArrayList<Integer>();
Arrays.sort(num);
result.add(item);//empty set
dfs(result, item, num, 0);
return result;
}
private void dfs(List<List<Integer>> result, List<Integer> item, int[] num, int pos){
for(int i=pos; i<num.length; i++){
item.add(num[i]);
result.add(new ArrayList<Integer>(item));
dfs(result, item, num, i+1);
item.remove(item.size()-1);
while(i<num.length-1 && num[i]==num[i+1])
i++;//ignore duplicate
}
}
}