78. 子集

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subsets
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

递归

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

class Solution {

    private List<List<Integer>> ret;

    private LinkedList<Integer> path;

    public Solution() {
        this.ret = new ArrayList<>();
        this.path = new LinkedList<>();
    }

    public void solve(int[] nums, int index) {
        if (index == nums.length) {
            ret.add(new ArrayList<>(path));
            return;
        }
        solve(nums, index + 1);
        path.offerLast(nums[index]);
        solve(nums, index + 1);
        path.pollLast();
    }

    public List<List<Integer>> subsets(int[] nums) {
        if (nums == null || nums.length == 0) {
            return Collections.emptyList();
        }
        solve(nums, 0);
        return ret;
    }
}

迭代

class Solution {
    List<Integer> t = new ArrayList<Integer>();
    List<List<Integer>> ans = new ArrayList<List<Integer>>();

    public List<List<Integer>> subsets(int[] nums) {
        int n = nums.length;
        for (int mask = 0; mask < (1 << n); ++mask) {
            t.clear();
            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-12-15 20:49  Tianyiya  阅读(32)  评论(0)    收藏  举报