回溯-子集

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;
    }
}
相关推荐
_olone14 小时前
AtCoder Beginner Contest 465 D - X to Y
c++·算法
青山木14 小时前
Hot 100 --- LRU 缓存
java·数据结构·算法·leetcode·链表·缓存·哈希
“码”力全开14 小时前
ONVIF摄像头接入项目实战记录
人工智能·算法·边缘计算
花生了什么事o14 小时前
Java 线程池:从参数到拒绝策略
java·jvm
长孙豪翔14 小时前
引发事件的问题
java·linux·数据库
happyprince14 小时前
09-vLLM KV Cache 系统完整分析
java·spring·vllm
掉鱼的猫14 小时前
ReActAgent 使用指南:构建会思考、能行动的 AI Agent
java·llm·agent
pp起床14 小时前
黑马点评 - 短信验证码登录实现
java·开发语言·tomcat
CodeStats14 小时前
《源纹天书》第121-125章:源匠归来——全栈重构与归元圣域的2.0时代
java·开发语言·源纹天书
AI人工智能+电脑小能手14 小时前
【大白话说Java面试题 第154题】【06_Spring篇】第14题:Spring 支持的 Bean 作用域
java·开发语言·spring·面试