回溯-子集

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;
    }
}
相关推荐
leobertlan1 小时前
痛苦系列 | DSP-03 跨越单位圆:Z变换与零极点分析
算法·程序员
蛋蛋的就会顺顺的2 小时前
hot100 p0——栈,贪心算法,动态规划
java·前端·javascript·算法·leetcode·力扣
需要8262 小时前
Spring Bean 生命周期:从实例化到销毁的完整钩子
java·后端·spring
开发小能手1232 小时前
答案daanC语言
数据结构·算法
小 黄 鸡2 小时前
HashMap 面试必会知识点详解(JDK 8)
java·面试·职场和发展
Navigator_Z4 小时前
LeetCode //C - 1291. Sequential Digits
c语言·算法·leetcode
伯恩bourne4 小时前
Spring Boot Bean 注册的两种方式:@Component 家族 vs @Configuration + @Bean
java·spring boot·后端
silvamux_4 小时前
curl 测试 OpenAI 兼容 API 的完整流程
java·人工智能·缓存·ai·oneapi
pride.li5 小时前
第03章 Python 教程-基础语法:注释与变量
服务器·前端·后端·python·算法·计算机视觉
省钱兄--zs5 小时前
深圳24小时自助健身房软硬件解决方案实战指南与开发流程详解
java·数据仓库·spring boot·小程序·架构