回溯-子集

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;
    }
}
相关推荐
噢,我明白了12 小时前
QueryWrapper的使用
java
Chase_______12 小时前
【Java基础 | 15】集合框架(中):Set、HashSet、TreeSet 与哈希表
java·windows·散列表
摇滚侠12 小时前
Maven 入门+高深 微服务案例 122-125
java·微服务·maven
QuZero12 小时前
Guava Cache Deep Dive
java·后端·算法·guava
随意起个昵称13 小时前
线性dp-LIS题目4(A Twisty Movement)
算法·动态规划
Felven13 小时前
B. Fair Numbers
数据结构·算法
人道领域13 小时前
【LeetCode刷题日记】93.复原IP地址
java·开发语言·算法·leetcode
jarreyer13 小时前
【算法记录1】模型训练问题
算法
Felven13 小时前
D. Friends and the Restaurant
算法
摇滚侠13 小时前
JavaWeb 全套教程 Listener 112-113
java·开发语言·servlet·tomcat·intellij-idea