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);


    }


}
相关推荐
ysu_03148 小时前
05 | 持久化撤销提示非核心功能
算法·游戏程序
浮沉9879 小时前
二分查找算法概述&通用模板
算法
Keven_1110 小时前
算法札记:SPFA判负环算法的证明
算法
什巳10 小时前
JAVA练习278- 和为 K 的子数组
java·学习·算法·leetcode
Jerry11 小时前
LeetCode 347. 前 K 个高频元素
算法
Young Doro11 小时前
SAC 算法
线性代数·算法·机器学习
罗超驿11 小时前
2.算法效率的核心密码:时间复杂度和空间复杂度详解
java·数据结构·算法
:-)12 小时前
算法-堆排序
数据结构·算法·排序算法