您的位置:首页 > 其它

leetcode - 90.Subsets II

2017-03-18 17:08 274 查看

Subsets II

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],
[]
]


Solution1:

public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
subsets(nums, 0, result, new ArrayList<>());
return result;
}

private void subsets(int[] nums, int begin, List<List<Integer>> result, List<Integer> temp) {
if (!result.contains(temp))
result.add(new ArrayList<>(temp));
for (int i = begin; i < nums.length; i++) {
temp.add(nums[i]);
subsets(nums, i + 1, result, temp);
temp.remove(temp.size() - 1);
}
}


Solution2:

better

public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
subsets(nums, 0, result, new ArrayList<>());
return result;
}

private void subsets(int[] nums, int begin, List<List<Integer>> result, List<Integer> temp) {
result.add(new ArrayList<>(temp));
for (int i = begin; i < nums.length; i++) {
if (i > begin && nums[i] == nums[i - 1])
continue;
temp.add(nums[i]);
subsets(nums, i + 1, result, temp);
temp.remove(temp.size() - 1);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode