回溯-子集

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;
    }
}
相关推荐
AI开源软件11 分钟前
Vue3+SpringBoot3 业务配置统一管理:接管、保存与回退怎样保留有效值
java·前端·vue.js·spring boot·vue·ruoyi office
陈如水33 分钟前
Spring AI Alibaba 在多 Agent 场景下的实践
java·人工智能·spring
console.log('npc')1 小时前
Python 学习教程 · 第4课:数据结构
数据结构·python·学习
吃我一窝jio1 小时前
Docker+Jenkins+K8s全流程部署
java·开发语言·笔记·python
橘子132 小时前
【高级数据库】关系代数基本概念
算法
Resean02234 小时前
Spring 源码分析(六)循环依赖与三级缓存
java·spring·缓存
在爪洼山玩泥巴4 小时前
fastjson2 JSONPath 取不存在路径,为什么会抛 “not support”?
java·开发语言·jsonpath·fastjson
电科_银尘13 小时前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
星落梦生14 小时前
SpringAOP基础笔记(7)
java·开发语言
金銀銅鐵15 小时前
带您看懂字节码指令(四):一条指令里有什么
java·jvm