回溯-子集

78.子集

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

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

输入 :整型数组
输出 :二元列表
思路:利用二进制,(比如说数组长度为3)000、001、010、011、100、101、110、111刚好可以遍历所有情况

java 复制代码
class Solution {
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> tempList = new ArrayList<>();
    public List<List<Integer>> subsets(int[] nums) {
        int n = nums.length;
        for(int i = 0; i < (1 << n); i++){
            tempList.clear();
            for(int j = 0; j < n; j++){
                if((i & (1 << j)) != 0){
                    tempList.add(nums[j]);
                }
            }
            result.add(new ArrayList<>(tempList));
        }
        return result;
    }
}
相关推荐
leobertlan1 小时前
痛苦系列 | DSP-04 截断时空的“窗”:FIR 滤波器设计与线性相位
算法
老师我太想进步了20261 小时前
【数据结构-12】树与二叉树的结构、概念
数据结构
jaysee-sjc1 小时前
【黑马点评】Day02:优惠券秒杀与分布式锁
java·分布式·nginx·spring·node.js·tomcat·maven
秋天的怀念_David2 小时前
算法一千零一夜 · 第三十五夜 · 恢复风暴
java·程序人生·算法
考虑考虑2 小时前
JDK27中的加密对象的 PEM 编码
java·后端·java ee
行者-全栈开发2 小时前
SpringBoot + GraalVM 原生编译实战:启动时间从8秒到0.5秒的极致优化
java·spring boot·后端
CoderYanger3 小时前
Java EE 进阶:10. MyBatis-Plus使用(第一弹)
java·spring boot·后端·sql·spring·java-ee·mybatis
泯泷4 小时前
别再“裸聊”大模型了!你家的 AI 为什么总胡说八道?根子在 RAG
人工智能·算法·架构
2601_967980115 小时前
Python中heapq模块的各种用法实例
数据结构·python·算法·应用实例·heapq模块