[leetcode]Subsets II

新博文地址:[leetcode]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],
[]
]

 很典型的递归,与Subsets区别的是,这道题,s是包含重复元素的,其实好像木有太大影响,只需要用一个set集合在过滤掉重复的list即可。

	List<List<Integer>> result = new ArrayList<List<Integer>>();
	Set<List<Integer>> resultSet = new HashSet<List<Integer>>();
	public List<List<Integer>> subsetsWithDup(int[] num) {
		List<Integer> nil = new ArrayList<Integer>();
		result.add(nil);
		if(num == null || num.length == 0){
			return result;
		}
		Arrays.sort(num);
		List<Integer> list =new ArrayList<Integer>();
		for(int i = 0 ; i < num.length; i++){
			list.add(num[i]);
			getSubSet(num, i, list);
			list.remove(list.size() - 1);
		}
		return result;
	}
	
	private void getSubSet(int[] num,int n,List<Integer> list){
		if(n < num.length){
			if(!resultSet.contains(list)){
				List<Integer> copy = new ArrayList<Integer>(list);
				result.add(copy);
				resultSet.add(copy);
			}
		}
		
		for(int i = n + 1; i < num.length; i++){
			list.add(num[i]);
			getSubSet(num,i,list);
			list.remove(list.size() - 1);
		}
	}

 

你可能感兴趣的:(LeetCode)