leetcode-子集

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

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

示例 1:

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

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

示例 2:

输入:nums = [0]

输出:[[],[0]]

提示:

1 <= nums.length <= 10

-10 <= nums[i] <= 10

nums 中的所有元素 互不相同

思路 :考虑两点。第一点,选过的数是否还可以选择?第二点,遍历数组选数的位置。对于第一点,选过的数不能被再次选择。对于第二点,一个数字有两种策略,选择或者不选择。不管是哪种策略,后面再选择数字时都不会再次考虑当前数字。

综合上面两点,每次考虑当前数字是否选择。下次递归调用时,考虑下一个数字的情况即可。即index+1。

代码

c 复制代码
class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        dfs(nums,0,new ArrayList<>(),res);
        return res;
    }

    public void dfs(int[] nums,int index,List<Integer> temp, List<List<Integer>> res){
        if(index==nums.length){
            res.add(new ArrayList<>(temp));
            return;
        }
        // xuan
        temp.add(nums[index]);
        dfs(nums,index+1,temp,res);
        temp.remove(temp.size()-1);
        // buxuan
        dfs(nums,index+1,temp,res);
    }
}
相关推荐
今儿敲了吗1 小时前
28| A-B数对
数据结构·c++·笔记·学习·算法
Desirediscipline1 小时前
#include<limits>#include <string>#include <sstream>#include <iomanip>
java·开发语言·前端·javascript·算法
Felven2 小时前
B. Luntik and Subsequences
算法
菜鸡儿齐2 小时前
leetcode-括号生成
算法·leetcode·职场和发展
fs哆哆2 小时前
在VB.NET中,随机打乱列表顺序的算法与方法
算法·.net
pen-ai2 小时前
【Yolo系列】Yolov3 目标检测算法原理详解
算法·yolo·目标检测
田里的水稻2 小时前
EP_基于UWB和单线激光雷达的托盘转送
人工智能·算法·数学建模·机器人·自动驾驶
List<String> error_P2 小时前
DFS(深度优先搜索)
数据结构·算法·dfs
今儿敲了吗2 小时前
27| 魔法封印
数据结构·c++·笔记·学习·算法