[Leetcode 90]求含有重复数的子集 Subset II

时间:2023-03-09 19:57:29
[Leetcode 90]求含有重复数的子集 Subset 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.

【思路】

注意sort,使得判断临接元素是否相邻。

与leetcode78类似,多了一个重复数判断条件

            if(i>flag&&nums[i-1]==nums[i])
continue
;

【相关题目】

1、[Leetcode 78]求子集 Subset https://www.cnblogs.com/inku/p/9976049.html

2、[Leetcode 90]求含有重复数的子集 Subset II https://www.cnblogs.com/inku/p/9976099.html

3、讲解在这: [Leetcode 216]求给定和的数集合 Combination Sum III

【代码】

public class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> ans=new ArrayList<>();
List<Integer> tmp=new ArrayList<>();
Arrays.sort(nums);
fun(nums,ans,tmp,0);
return ans;
} public void fun(int nums[],List<List<Integer>> ans,List<Integer> tmp,int flag){
ans.add(new ArrayList<>(tmp));
for(int i=flag;i<nums.length;i++){
if(i>flag&&nums[i-1]==nums[i])
continue
;
tmp.add(nums[i]);
fun(nums,ans,tmp,i+1);
tmp.remove(tmp.size()-1);
}
}
}