https://leetcode.com/problems/subsets-ii/#/description
问题描述:
寻找重复元素子集合,解集合中不可以有相同的子集。
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
思路解析:
递归的方式求解,建立一个function,getSubset(int[] nums,int pos ,List< List< Integer>> result,List< Integer> temp) 记录当前位置,为了处理当前子集中的每个元素,都存储到temp链表中,每返回一层,清空当前层添加进去的元素,目的是返回上一层是,temp链表是同进入递归之前的是一样的。
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result=new ArrayList<>();
getSubset(nums,0,result,new ArrayList<>());
return result;
}
public void getSubset(int[] nums,int pos ,List<List<Integer>> result,List<Integer> temp)
{
if(pos<=nums.length) result.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]);
getSubset(nums,i+1,result,temp);
temp.remove(temp.size()-1);//每返回一层,清空当前层添加进去的元素。
}
}
}