码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Subsets II

时间:2015-04-14 23:20:22      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

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],
  []
]
题意:输出组合,不能重复。

思路:再普通组合的情况下加上一个条件就是如果排序后数字重复的话,我们就只取第一个。

public class Solution {
    public List<List<Integer> > ans = new ArrayList<List<Integer> >();
	
	void dfs(int[] num, List<Integer> tmp, int cur) {
		List<Integer> t = new ArrayList<Integer>(tmp);
		ans.add(t);
		
		for (int i = cur; i < num.length; i++) {
			if (i != cur && num[i] == num[i-1]) continue;
			tmp.add(num[i]);
			dfs(num, tmp, i+1);
			tmp.remove(tmp.size()-1);
		}
	}
	
    public List<List<Integer> > subsetsWithDup(int[] num) {
    	Arrays.sort(num);
    	ans.clear();
    	List<Integer> tmp = new ArrayList<Integer>();
    	dfs(num, tmp, 0);
    	for (List<Integer> i : ans) 
    		System.out.println(i.toString());
    	return ans;
    }
}



LeetCode Subsets II

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/45049659

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!