leetcode-子集

给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。

解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

示例 1:

输入:nums = 1,2,3

输出:\[,1,2,1,2,3,1,3,2,3,1,2,3]

示例 2:

输入:nums = 0

输出:\[,0]

提示:

1 <= nums.length <= 10

-10 <= numsi <= 10

nums 中的所有元素 互不相同

思路 :考虑两点。第一点,选过的数是否还可以选择?第二点,遍历数组选数的位置。对于第一点,选过的数不能被再次选择。对于第二点,一个数字有两种策略,选择或者不选择。不管是哪种策略,后面再选择数字时都不会再次考虑当前数字。

综合上面两点,每次考虑当前数字是否选择。下次递归调用时,考虑下一个数字的情况即可。即index+1。

代码:

c 复制代码
class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        dfs(nums,0,new ArrayList<>(),res);
        return res;
    }

    public void dfs(int[] nums,int index,List<Integer> temp, List<List<Integer>> res){
        if(index==nums.length){
            res.add(new ArrayList<>(temp));
            return;
        }
        // xuan
        temp.add(nums[index]);
        dfs(nums,index+1,temp,res);
        temp.remove(temp.size()-1);
        // buxuan
        dfs(nums,index+1,temp,res);
    }
}
相关推荐
民乐团扒谱机10 小时前
【超详细】基频音高提取算法之SWIPE 算法深度解析:频谱匹配的精度极限与工程边界
人工智能·算法
饮水桶_T10 小时前
C++ stack & queue复习笔记
开发语言·笔记·算法
wy_hhxx11 小时前
[Leetcode] 滑动窗口
算法·leetcode·滑动窗口
码途行者11 小时前
每天10分钟学Go:第20课 泛型
c++·算法·golang
AIgorithmGEEK13 小时前
算法·哈希表|从“逐个比”到“按 key 算位置”
数据结构·c++·算法·leetcode·hash
风落青芜15 小时前
排序算法(二):选择排序、堆排序与冒泡排序
c语言·开发语言·数据结构·算法·排序算法
Navigator_Z15 小时前
LeetCode //C - 1319. Number of Operations to Make Network Connected
c语言·算法·leetcode
h_a_o777oah16 小时前
【数据结构】FHQ Treap:无旋转的平衡 BST
数据结构·c++·算法·acm·平衡树·treap·fhq treap
草履虫AI课16 小时前
强化学习从零到一 07|重要性采样:借别人的数据,算自己的期望
算法·强化学习