LintCode-----17.帶重複元素的子集
阿新 • • 發佈:2019-01-28
加上去重複的條件就是了沒注意一定要先sort一下
public class Solution {
/*
* @param nums: A set of numbers.
* @return: A list of lists. All valid subsets.
*/
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> item = new ArrayList<>();
if (nums == null) {
return result;
}
if (nums.length == 0) {
result.add(item);
return result;
}
Arrays.sort(nums);
for (int i = 0; i <= nums.length; i++) {
item.clear();
dfs(nums, 0 , i, item, result);
}
return result;
}
public void dfs(int[] nums, int step, int size, List<Integer> item, List<List<Integer>> result) {
if (step == size) {
result.add(new ArrayList<>(item));
return;
}
for (int i = step; i < nums.length; i++) {
if (i != step && nums[i] == nums[i - 1]) {
continue;
}
item.add(nums[i]);
dfs(nums, i + 1, size, item, result);
item.remove(item.size() - 1);
}
}
}