【题目】
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;
【代码】
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); } } }
原文地址:https://www.cnblogs.com/inku/p/9976099.html
时间: 2024-10-08 16:06:31