Java for LeetCode 090 Subsets II

时间:2015-05-20 02:02:01   收藏:0   阅读:154

Given a collection of integers that might contain duplicates, nums, return all possible subsets.

Note:

For example,
If nums = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

解题思路一:

偷懒做法,将Java for LeetCode 078 Subsets中的List换为Set即可通过测试,JAVA实现如下:

public List<List<Integer>> subsetsWithDup(int[] nums) {
	    Set<List<Integer>> list = new HashSet<List<Integer>>();
	    list.add(new ArrayList<Integer>());
	    Arrays.sort(nums);
	    for(int i=1;i<=nums.length;i++)
	        dfs(list, nums.length, i, 0,nums,-1);
	    return new ArrayList(list);
	}
	 
	static List<Integer> alist = new ArrayList<Integer>();
	 
	static void dfs(Set<List<Integer>> list, int n, int k, int depth,int[] nums,int last) {
	    if (depth >= k) {
	        list.add(new ArrayList<Integer>(alist));
	        return;
	    }
	    for (int i = last+1; i <= n-k+depth; i++) {
	        alist.add(nums[i]);
	        dfs(list, n, k, depth + 1,nums,i);
	        alist.remove(alist.size() - 1);
	    }
	}

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!