回溯-子集

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;
    }
}
相关推荐
WiChP23 分钟前
【V0.1B5】从零开始的2D游戏引擎开发之路
java·服务器·数据库
cch891830 分钟前
汇编与Java:底层与高层的编程对决
java·开发语言·汇编
荒川之神1 小时前
拉链表概念与基本设计
java·开发语言·数据库
cch89182 小时前
汇编与Go:底层到高层的编程差异
java·汇编·golang
workflower2 小时前
用硬件换时间”与“用算法降成本”之间的博弈
人工智能·算法·安全·集成测试·无人机·ai编程
chushiyunen2 小时前
python中的@Property和@Setter
java·开发语言·python
禾小西2 小时前
Java中使用正则表达式核心解析
java·python·正则表达式
yoyo_zzm2 小时前
JAVA (Springboot) i18n国际化语言配置
java·spring boot·python
APIshop2 小时前
Java获取京东商品详情接口(item_get)实战指南
java·linux·数据库