子集

给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。

解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

示例 1:

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

输入:nums = [0]
输出:[[],[0]]

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/subsets
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        return dfs(0,nums,res,new ArrayList<Integer>());
    }
    public List<List<Integer>> dfs(int j, int[] nums, List<List<Integer>> res, ArrayList<Integer> tmp){
        //每次放入新的内存地址数据,不然影响之前存入的数据
        res.add(new ArrayList<>(tmp));
        for(int i = j;i<nums.length;i++){
            //更新每次放入的数据
            //1;1,2;1,2,3;
            tmp.add(nums[i]);
            //递归遍历;
            dfs(i+1,nums,res,tmp);
            //回溯
            tmp.remove(tmp.size()-1);
        }
        return res;
    }
}
posted @ 2022-12-14 23:32  网抑云黑胶SVIP用户  阅读(105)  评论(0)    收藏  举报