1. 程式人生 > >[Leetcode 90]求含有重複數的子集 Subset II

[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
;

【程式碼】

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); } } }