回溯-子集

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;
    }
}
相关推荐
宇木灵13 小时前
C语言基础-六、指针
c语言·开发语言·学习·算法
苦藤新鸡13 小时前
64 搜索平移递增数组中的元素
数据结构·算法
百锦再13 小时前
Java InputStream和OutputStream实现类完全指南
java·开发语言·spring boot·python·struts·spring cloud·kafka
Vic1010113 小时前
链表算法三道
java·数据结构·算法·链表
二年级程序员13 小时前
一篇文章掌握“栈”
c语言·数据结构
再难也得平13 小时前
[LeetCode刷题]128.最长连续序列(从零开始的java题解)
java·算法·leetcode
亓才孓13 小时前
【MyBatis Exception】SQLSyntaxErrorException(按批修改不加配置会报错)
java·开发语言·mybatis
xiaoye-duck14 小时前
《算法题讲解指南:优选算法-双指针》--05有效三角形的个数,06查找总价值为目标值的两个商品
c++·算法
亓才孓14 小时前
【MyBatis Runtime Exception】自动驼峰映射对Map不生效,应该在查询中起别名
java·windows·mybatis
ArturiaZ14 小时前
【day31】
开发语言·c++·算法