Subsets II

LeetCode Q 78 - Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:
Input: [1,2,2]
Output:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]

Solution : Backtracking

Code:

private List<List<Integer>> res;
public List<List<Integer>> subsets(int[] nums) {
	res = new ArrayList<>();
	if (nums == null || nums.length == 0) return res;
	Arrays.sort(nums);
	backtrack(nums, 0, new ArrayList<>());
	return res;
}

private void backtrack(int[] nums, int pos, List<Integer> temp) {
	res.add(new ArrayList(temp));

	for (int i = pos; i < nums.length; i++) {
		if (i != pos && nums[i] == nums[i - 1]) continue;
		temp.add(nums[i]);
		backtrack(nums, i + 1, temp);
		temp.remove(temp.size() - 1);
	}
}

   Reprint policy


《Subsets II》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC