LeetCode 90 Subsets II

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 wr
个人分类: LeetCode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭