回溯-子集

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;
    }
}
相关推荐
总斯霖3 分钟前
HDU 4857 - 逃生 题解
算法
咖啡啡不加糖4 分钟前
Arthas 使用指南:Java 应用诊断利器
java·spring boot·后端
-To be number.wan4 分钟前
算法学习日记 | 模拟
c++·学习·算法
Blossom.1185 分钟前
从“金鱼记忆“到“超级大脑“:2025年AI智能体记忆机制与MoE架构的融合革命
人工智能·python·算法·架构·自动化·whisper·哈希算法
金枪不摆鳍5 分钟前
算法-贪心算法
算法·贪心算法
naruto_lnq5 分钟前
高性能消息队列实现
开发语言·c++·算法
小北方城市网5 分钟前
MongoDB 分布式存储与查询优化:从副本集到分片集群
java·spring boot·redis·分布式·wpf
池央7 分钟前
贪心算法-摆动序列
算法·贪心算法
想逃离铁厂的老铁8 分钟前
Day60 >> 94、城市间货物运输1️⃣ + 95、城市间货物运输 2️⃣ + 96、城市间货物运输 3️⃣
java·服务器·前端
AndrewHZ8 分钟前
【AI黑话日日新】什么是隐式CoT?
人工智能·深度学习·算法·llm·cot·复杂推理