回溯-子集

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;
    }
}
相关推荐
ZC跨境爬虫13 小时前
LeetCode 219. 存在重复元素 II(滑动窗口 + 哈希表详解)
算法·leetcode·散列表
吞下星星的少年·-·13 小时前
The 2025 ICPC Asia East Continent Online Contest (I) A题(模拟+贪心)
算法·贪心·模拟
2601_9620715713 小时前
数据库系统架构与DBMS功能探微:现代信息时代数据管理的关键
java·开发语言·数据库
梦想的旅途213 小时前
如何高效调用企业微信通讯录API管理组织架构
java·开发语言·企业微信
小程序设计13 小时前
【机械设计】磁粉检测机器人的设计与验证
算法·机器人
Navigator_Z13 小时前
LeetCode //C - 1220. Count Vowels Permutation
c语言·算法·leetcode
2601_9620652514 小时前
2.启动mysql容器
java·数据库·mysql
2601_9620654914 小时前
PHP For 循环
android·java·php
吃好睡好便好14 小时前
判断函数的使用
学习·算法·matlab·生活·判断函数
2601_9561219714 小时前
线性DP(入门)
c++·算法·动态规划