给定一个可能具有重复数字的列表,返回其所有可能的子集
样例
如果S = [1,2,2],一个可能的答案为:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
挑战
你可以同时用递归与非递归的方式解决么?
注意事项
- 子集中的每个元素都是非降序的
- 两个子集间的顺序是无关紧要的
解集中不能包含重复子集
解题思路:
几乎与Lintcode 17.子集 一模一样,只是在循环中增加了一个条件判断跳过重复元素。
public class Solution {
/**
* @param nums: A set of numbers.
* @return: A list of lists. All valid subsets.
*/
public List<List<Integer>> subsetsWithDup(int[] nums) {
// write your code here
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
dfs(nums, new ArrayList<Integer>(), res, 0);
return res;
}
private void dfs(int[] nums, List<Integer> list, List<List<Integer>> res, int index){
res.add(new ArrayList<Integer>(list));
for(int i = index; i < nums.length; i++){
if(i != index && nums[i] == nums[i-1])
continue;
list.add(nums[i]);
dfs(nums, list, res, i + 1);
list.remove(list.size() - 1);
}
}
}

本文介绍了一种算法,用于生成包含重复数字列表的所有可能子集,并确保输出中没有重复的子集。通过先对输入进行排序并使用递归深度优先搜索的方法,在遍历过程中跳过重复元素来实现这一目标。

378

被折叠的 条评论
为什么被折叠?



