leetcode第90题子集|| (回溯+去重) √

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/m0_37719047/article/details/102723359

给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

输入: [1,2,2]
输出:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>>  ret=new ArrayList<List<Integer>>();
        List<Integer> list=new ArrayList<Integer>();
        subsetsWithDup(nums,ret,list,0);
        return ret;
        
    }
    public void subsetsWithDup(int[] ns,List<List<Integer>>  ret,List<Integer> list,int start) {
        ret.add(new ArrayList(list));
        for(int i=start;i<ns.length;i++){
            if(i!=start&&ns[i]==ns[i-1]) continue;
            int temp=ns[i];
            list.add(temp);
            subsetsWithDup(ns,ret,list,i+1);
            list.remove(list.size()-1);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37719047/article/details/102723359