leetcode-90. Subsets II(重复元素子集合)

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);//每返回一层,清空当前层添加进去的元素。

        }






    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值