您的位置:首页 > 编程语言 > Java开发

(java)Subsets II

2016-03-08 13:19 375 查看
Given a collection of integers that might contain duplicates, nums, 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 nums =
[1,2,2]
,
a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]


思路:这个与I的区别就是里面有重复的数字,我们可以通过set<List<Integer>>过滤下重复的List<Integer>就行
代码如下(已通过leetcode)
public class Solution {

public List<List<Integer>> subsetsWithDup(int[] nums) {

List<List<Integer>> lists=new ArrayList<List<Integer>>();

List<Integer> list=new ArrayList<Integer>();

lists.add(list);

int n=nums.length;

if(n==0||nums==null) return lists;

Set<List<Integer>> sets=new HashSet<List<Integer>>();

Arrays.sort(nums);

for(int i=1;i<=n;i++) {

dfs(nums,sets,list,0,i);

}

//System.out.println("sets:"+sets.size());

Iterator<List<Integer>> it=sets.iterator();

while(it.hasNext()) {

lists.add(it.next());

}

return lists;

}

private void dfs(int[] nums, Set<List<Integer>> sets, List<Integer> list, int start, int number) {

// TODO Auto-generated method stub

if(number==list.size()) {

sets.add(new ArrayList<Integer>(list));

return;

}

for(int i=start;i<nums.length;i++) {

list.add(nums[i]);

dfs(nums,sets,list,i+1,number);

list.remove(list.size()-1);

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: