LeetCode - Medium - 90. Subsets II

Topic

  • Array
  • Backtracking

Description

https://leetcode.com/problems/subsets-ii/

Given an integer array nums that may contain duplicates, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

Example 1:

Input: nums = [1,2,2]
Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]

Example 2:

Input: nums = [0]
Output: [[],[0]]

Constraints:

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10

Analysis

本题与LeetCode - Medium - 78. Subsets类似,区别在于解法多了排序原数组和跳过重复元素。

用示例中的[1, 2, 2] 来举例,如图所示:(「注意去重需要先对集合排序」)

从图中可以看出,同一树层上重复取2 就要过滤掉,同一树枝上就可以重复取2,因为同一树枝上元素的集合才是唯一子集!

参考文献

  1. 回溯算法:求子集问题(二)

Submission

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SubsetsII {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
    	List<List<Integer>> result = new ArrayList<>();
    	List<Integer> path = new ArrayList<>();
    	boolean[] used = new boolean[nums.length];
    	Arrays.sort(nums);
    	backtracking(path, nums, used, 0, result);
        return result;
    }
    
    private void backtracking(List<Integer> path, int[] nums, boolean[] used, // 
    		int startIndex, List<List<Integer>> result) {
    	
    	result.add(new ArrayList<>(path));
    	
    	for(int i = startIndex; i < nums.length; i++) {
    		if(i > 0 && nums[i - 1] == nums[i] && !used[i - 1])
    			continue;
    		
    		used[i] = true;
    		path.add(nums[i]);
    		backtracking(path, nums, used, i + 1, result);
    		path.remove(path.size() - 1);
    		used[i] = false;
    	}
    }
    
}

Test

import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.List;

import static org.hamcrest.collection.IsIterableContainingInAnyOrder.*;
import org.junit.Test;

public class SubsetsIITest {

	@Test
	@SuppressWarnings("unchecked")
	public void test() {
		SubsetsII obj = new SubsetsII();

		
		List<List<Integer>> result = obj.subsetsWithDup(new int[] {1, 2, 2});
		System.out.println(result);
		assertThat(result, // 
				containsInAnyOrder(Arrays.asList(), Arrays.asList(1), Arrays.asList(1, 2), //
						Arrays.asList(1, 2, 2), Arrays.asList(2), Arrays.asList(2, 2)));
		
		assertThat(obj.subsetsWithDup(new int[] {0}), //
				containsInAnyOrder(Arrays.asList(), Arrays.asList(0)));
		
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值