回溯-子集

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;
    }
}
相关推荐
想做后端的小C7 分钟前
Java:接口回调
java·开发语言·接口回调
浅川.2518 分钟前
STL专项:stack 栈
数据结构·stl·stack
爱学习的小可爱卢19 分钟前
JavaEE进阶——Spring核心设计模式深度剖析
java·spring·设计模式
毕设源码-钟学长1 小时前
【开题答辩全过程】以 个性化电影推荐网站的设计与实现为例,包含答辩的问题和答案
java·spring boot
C++业余爱好者1 小时前
Power Job 快速搭建 及通信机制介绍
java
YGGP1 小时前
【Golang】LeetCode 32. 最长有效括号
算法·leetcode
自然常数e1 小时前
字符函数和字符串函数
c语言·算法·visual studio
qq_2704900961 小时前
SpringBoot药品管理系统设计实现
java·spring boot·后端
youngee112 小时前
hot100-56最小栈
数据结构