回溯-子集

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;
    }
}
相关推荐
学长毕设19 分钟前
基于SpringBoot的建筑材料管理系统-附源码
java·spring boot·后端
摸爬滚打的小李42 分钟前
关于 Arthas
java·后端
程序员清风1 小时前
算法题中的边界条件、测试与调试
开发语言·算法·kotlin
砚底藏山河1 小时前
python量化实操:冷热分层存储
java·开发语言·python·金融
yuniko-n1 小时前
【JUC】原子类
java
惊讶的猫1 小时前
Query 改写
java·rag
炘爚1 小时前
数据结构算法总结
数据结构·python·算法
信誓旦旦的程序猿1 小时前
【Python量化实战宝典 #18】MACD 金叉死叉手册:DIF、DEA、柱体全拆解(Python 可跑)
java·python·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
Dageno_AI2 小时前
ChatGPT 不再引用 Reddit 之后,还值得在 Reddit 上做 AI 可见度吗?
算法
hetao17338372 小时前
2026-10-25 hetao1733837 的刷题记录
c++·算法