回溯-子集

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;
    }
}
相关推荐
光依旧11 小时前
MCP实战手记系列(二):跑通第一个 MCP Server(文末附github源码链接)
java·spring ai·mcp·ai 开发·源码实战
All for pursuit.11 小时前
【链表-9】146.LRU缓存
数据结构·c++·算法·leetcode
木子算法11 小时前
测出来的值会抖:约束和目标带噪声时,「可行」和「更好」该怎么判
人工智能·算法·目标跟踪
白远山11 小时前
上海24小时自助健身房系统软件开发实战指南:从需求到部署
java·架构·uni-app·需求分析
MayBaymax12 小时前
Spring AI Alibaba Graph 快速上手:黑板、节点、边
java·spring·ai·ai编程
斑鸠喳喳12 小时前
可重入锁 ReentrantLock
java·源码
IT枫斗者枫哥12 小时前
Spring AI 聊天记忆落库:重启后,怎样接上上一轮对话
java
devpotato12 小时前
HashMap 扩容机制:从源码细节到工程实践
java
yueping212 小时前
如何用idea打开jar包
java
IT_Octopus12 小时前
从一个应用开发者的角度,搞懂大数据查询的完整链路
java·大数据·数据库