回溯-子集

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;
    }
}
相关推荐
prince_zxill9 分钟前
探索Nautilus Trader:高性能算法交易平台与事件驱动回测引擎的全面指南
算法
廋到被风吹走12 分钟前
设计原则深度解析:高内聚低耦合、模块边界与服务拆分
java
进击的荆棘15 分钟前
算法——二分查找
c++·算法·leetcode
识君啊16 分钟前
Java 滑动窗口 - 附LeetCode经典题解
java·算法·leetcode·滑动窗口
Zachery Pole18 分钟前
JAVA_08_封装、继承和多态
java·开发语言
烟花落o19 分钟前
【数据结构系列02】轮转数组、返回倒数第k个节点
数据结构·算法·leetcode·刷题
白露与泡影20 分钟前
Java 春招高级面试指南( Java 面试者必备)
java·开发语言·面试
努力也学不会java20 分钟前
【Spring Cloud】统一服务入口-Gateway
后端·算法·spring·spring cloud·gateway·服务发现
追随者永远是胜利者24 分钟前
(LeetCode-Hot100)3. 无重复字符的最长子串
java·算法·leetcode·职场和发展·go