LeetCode 90 Subsets II

原创 2016年06月01日 13:47:35

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],
  []
]

方法一:正常迭代

	public List<List<Integer>> subsetsWithDup3(int[] nums) {
		List<List<Integer>> result = new ArrayList<List<Integer>>();
		List<Integer> subSets = new ArrayList<Integer>();
		result.add(subSets);
		Arrays.sort(nums);
		int len = 0, start;
		for (int i = 0; i < nums.length; i++) {
			/**nums[i-1]已经和前面的子集并在一起作为subSets了,nums[i]==nums[i-1]就不要再做同样的事情了*/
			if (i != 0 && nums[i] != nums[i - 1]) start = 0;
			else start = len;
			len = result.size();
			for (int j = start; j < len; j++) {
				List<Integer> temp = new ArrayList<>(result.get(j));
				temp.add(nums[i]);
				result.add(temp);
			}
		}
		return result;
	}
方法二:递归

	public List<List<Integer>> subsetsWithDup(int[] nums) {
		List<List<Integer>> result = new ArrayList<>();
		Arrays.sort(nums);
		getSubsetsWithDup(result, new ArrayList<Integer>(), nums, 0);
		return result;
	}

	private void getSubsetsWithDup(List<List<Integer>> result, List<Integer> list, int[] nums, int start) {
		result.add(new ArrayList<Integer>(list));
		for (int i = start; i < nums.length; i++) {
			if (i > start && nums[i] == nums[i - 1]) continue;
			list.add(nums[i]);
			getSubsets(result, list, nums, i + 1);
			list.remove(list.size() - 1);
		}
	}


相关文章推荐

leetcode 90. Subsets II

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

【leetcode】90. Subsets II

leetcode, subsets ||, 3种解法

[leetcode 78 & 90, Medium] Subsets I and II

Subsets I and II

leetcode 90 Subsets II

leetcode 90 Subsets II c++ Python

LeetCode 90 Subsets II--In C++

思路: 由于这道题增加了冗余的属性,所以如果用Subset 1中的暴力递归进行求解的话,会浪费很多时间在扫描判断是否有重复值上。因此,类似于全排列的那个题,想到了在之前的基础上添加一个元素即可形成全...

LeetCode 78, 90. Subsets i, ii

1. 题目描述 Given a set of distinct integers, nums, return all possible subsets. Note: Element...

【LeetCode】90. Subsets II解法及注释

90. Subsets II Total Accepted: 65104 Total Submissions: 214320 Difficulty: Medium Given a collecti...

[LeetCode]90.Subsets II

题目Given a collection of integers that might contain duplicates, S, return all possible subsets.Note:...

Leetcode 90 - Subsets II(Search)

题意生成一个数组的所以子集。思路和之前的subsets一样,但是关键问题是要去重。算法1很暴力,用一个set套一个multiset来判断当前结果是否出现过。算法2我们先将数组排序,然后开始考虑怎么去重...
  • Lzedo
  • Lzedo
  • 2017年02月17日 20:51
  • 111

LeetCode #90 - Subsets II - Medium

Subsets Series Subsets I: http://blog.csdn.net/arcome/article/details/53888806 Subsets II: P...
  • Arcome
  • Arcome
  • 2016年12月26日 20:01
  • 146
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode 90 Subsets II
举报原因:
原因补充:

(最多只允许输入30个字)