leetcode 第78题 子集(回溯)√

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

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

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

示例:

输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

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

猜你喜欢

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