回溯-子集

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;
    }
}
相关推荐
小雉系统2 小时前
BcoreOS安全通信架构:FsSession 抗算法后门安全设计
算法·安全·架构
金銀銅鐵2 小时前
带您看懂字节码指令(二):空循环里有什么
java·后端·ai编程
吴名氏.4 小时前
Java转AI Agent教程(第十三周)混合检索与重排
java·数据库·人工智能·ai·ai agent
.痞老板.5 小时前
java ee--多线程(进阶)
java·java-ee
Pniubi5 小时前
关于算法用现成数据结构和手撕
数据结构
深入云栈6 小时前
Netty 4.2.x 源码深度解析 (二十三):ByteBuf 核心设计 —— 索引、类型与零拷贝
java·后端·架构
唐墨1236 小时前
linux kernel 比较数据大小的宏定义
linux·算法
拂拉氏7 小时前
【知识讲解-题目讲解】 统计满足K约束的子字符串数量2 (滑动窗口+前缀和+二分查找+分析)
算法·前缀和·二分查找·滑动窗口
wang_shu_mo_ran7 小时前
MyBatis 从入门到进阶(一)
java·spring·mybatis