首页 > 代码库 > Subsets II
Subsets II
题目
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], [] ]
方法
利用DFS,一层相同的元素不要放入即可。public void getSets(int[] S, int start, int end, List<List<Integer>> list, List<Integer> subList) { list.add(subList); int pre = Integer.MIN_VALUE; for (int i = start; i < end; i++) { List<Integer> newSubList = new ArrayList<Integer>(subList); int cur = S[i]; if (pre != cur) { newSubList.add(S[i]); getSets(S, i + 1, end, list, newSubList); pre = cur; } } } public List<List<Integer>> subsetsWithDup(int[] num) { Arrays.sort(num); List<List<Integer>> list = new ArrayList<List<Integer>>(); List<Integer> subList = new ArrayList<Integer>(); getSets(num, 0, num.length, list, subList); return list; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。