Loading

Medium | LeetCode 78. 子集 | 回溯

78. 子集

给你一个整数数组 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 <= nums[i] <= 10
  • nums 中的所有元素 互不相同

解题思路

方法一: 回溯法

class Solution {
    private List<List<Integer>> res;
 
    public List<List<Integer>> subsets(int[] nums) {
        res = new ArrayList<List<Integer>>();
        getSubSets(nums, 0, new LinkedList<>());
        return res;
    }

    public void getSubSets(int[] nums, int index, LinkedList<Integer> curSet) {
        // 递归出口
        if (index == nums.length) {
            res.add(new ArrayList<>(curSet));
            return;
        }
        // 先把当前元素加进集合
        curSet.addLast(nums[index]);
        // 递归后面的部分
        getSubSets(nums, index + 1, curSet);
        // 然后移除当前元素
        curSet.removeLast();
        // 递归后面的部分
        getSubSets(nums, index + 1, curSet);
    }
}

方法二:枚举

每个数字添加或者不添加, 有2^N 中情况。可以使用从0到2^N的数字的二进制为掩码, 来标记, 每个数字是否出现。

public List<List<Integer>> subsets(int[] nums) {
    int n = nums.length;
    List<Integer> t = new ArrayList<Integer>();
	List<List<Integer>> ans = new ArrayList<List<Integer>>();
    // 第一个For循环, 枚举2^N中情况
    for (int mask = 0; mask < (1 << n); ++mask) {
        t.clear();
        // 第二个For循环, 遍历掩码的每一位, 选取相应的数字
        for (int i = 0; i < n; ++i) {
            if ((mask & (1 << i)) != 0) {
                t.add(nums[i]);
            }
        }
        // 将每一个掩码对应的一组数字加进结果集
        ans.add(new ArrayList<Integer>(t));
    }
    return ans;
}
posted @ 2021-02-01 23:45  反身而诚、  阅读(39)  评论(0编辑  收藏  举报