回溯-子集

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;
    }
}
相关推荐
木子n14 分钟前
第2篇:坐标变换与数学基础:FOC算法的核心数学工具
算法·电机控制·foc
Rsun045517 分钟前
10、Java 桥接模式从入门到实战
java·开发语言·桥接模式
金銀銅鐵9 分钟前
[Java] 从 class 文件看 cglib 对 MethodInterceptor 的处理 (下)
java·后端
lee_curry12 分钟前
Java中关于“锁”的那些事
java·线程·并发·juc
阿Y加油吧17 分钟前
两道经典 DP 题:零钱兑换 & 单词拆分(完全背包 + 字符串 DP)
算法
pearlthriving18 分钟前
c++当中的泛型思想以及c++11部分新特性
java·开发语言·c++
疯狂打码的少年25 分钟前
有序线性表删除一个元素:顺序存储 vs 单链表,平均要移动多少个元素?
数据结构·算法·链表
y = xⁿ40 分钟前
20天速通LeetCode day07:前缀和
数据结构·算法·leetcode
梦魇星虹43 分钟前
idea Cannot find declaration to go to
java·ide·intellij-idea
小雅痞1 小时前
[Java][Leetcode hard] 42. 接雨水
java·开发语言·leetcode