回溯-子集

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;
    }
}
相关推荐
csdn_aspnet4 分钟前
C# (QuickSort using Random Pivoting)使用随机枢轴的快速排序
数据结构·算法·c#·排序算法
亚历克斯神11 分钟前
JVM 内存管理 2026:深度解析与调优实战
java·spring·微服务
鹿角片ljp19 分钟前
最长回文子串(LeetCode 5)详解
算法·leetcode·职场和发展
逻辑驱动的ken1 小时前
Java高频面试题:03
java·开发语言·面试·求职招聘·春招
广师大-Wzx1 小时前
一篇文章看懂MySQL数据库(下)
java·开发语言·数据结构·数据库·windows·python·mysql
野生技术架构师1 小时前
Java NIO到底是个什么东西?
java·开发语言·nio
paeamecium2 小时前
【PAT甲级真题】- Cars on Campus (30)
数据结构·c++·算法·pat考试·pat
likerhood3 小时前
简单工厂设计模式
java·ide·intellij-idea
chh5633 小时前
C++--模版初阶
c语言·开发语言·c++·学习·算法
RTC老炮3 小时前
带宽估计算法(gcc++)架构设计及优化
网络·算法·webrtc