LeetCode78 子集

题目:

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

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

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

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

思路:

  • 回溯法
  • 选择数组元素,如果数组元素全都选择完了,就添加到结果集里面
  • 回溯移除最后添加的数组元素,移除后再次进行递归添加新的子集

代码:

class LeetCode78 {
    //存放结果集
    List<List<Integer>> resultList = new ArrayList<>();
    //存放已经被选中的数据
    List<Integer> list = new ArrayList<>();    


    public List<List<Integer>> subsets(int[] nums) {
        //回溯法 
        dfs (0, nums);

        return resultList;

    }

    public void dfs (int cur, int[] nums) {
        //如果全都选择完了,就添加到结果集里面
        if (cur == nums.length) {
            resultList.add(new ArrayList<Integer>(list));
            return;
        }
        //选择数组元素
        list.add( nums[cur]);
        //递归
        dfs(cur+1, nums);
        //回溯,移除刚添加的(也就是最后一个)元素,以便后面再重新选择
        list.remove( list.size()-1);
        // 移除后一个元素后,再次进行递归添加新的子集到list中
        dfs(cur+1, nums);


    }


}

posted on   乐之者v  阅读(7)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示