题目

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

  1. Input: nums = [1,2,3]
  2. Output:
  3. [
  4. [3],
  5. [1],
  6. [2],
  7. [1,2,3],
  8. [1,3],
  9. [2,3],
  10. [1,2],
  11. []
  12. ]

题意

求一个数组的幂集(即所有子集,包括全集和空集,构成的集族)。

思路

回溯法。

也可以利用位运算来求子集,具体方法参考 LeetCode 78. Subsets (位运算入门:利用位运算求子集)

也可以直接循环迭代处理。


代码实现

Java

回溯法

  1. class Solution {
  2. public List<List<Integer>> subsets(int[] nums) {
  3. List<List<Integer>> ans = new ArrayList<>();
  4. subsets(nums, 0, new ArrayList<>(), ans);
  5. return ans;
  6. }
  7. private void subsets(int[] nums, int index, List<Integer> list, List<List<Integer>> ans) {
  8. if (index == nums.length) {
  9. ans.add(new ArrayList<>(list));
  10. return;
  11. }
  12. subsets(nums, index + 1, list, ans);
  13. list.add(nums[index]);
  14. subsets(nums, index + 1, list, ans);
  15. list.remove(list.size() - 1);
  16. }
  17. }

位运算

  1. class Solution {
  2. public List<List<Integer>> subsets(int[] nums) {
  3. List<List<Integer>> ans = new ArrayList<>();
  4. List<Integer> list = new ArrayList<>();
  5. int all = 1 << (nums.length); // 总情况数
  6. for (int i = 0; i < all; i++) {
  7. // 判断数组中每一个数是否应该添加
  8. for (int j = 0; j < nums.length; j++) {
  9. if ((i & (1 << j)) > 0) {
  10. list.add(nums[j]);
  11. }
  12. }
  13. ans.add(new ArrayList<>(list));
  14. list.clear();
  15. }
  16. return ans;
  17. }
  18. }

JavaScript

回溯法

  1. /**
  2. * @param {number[]} nums
  3. * @return {number[][]}
  4. */
  5. var subsets = function (nums) {
  6. let lists = []
  7. dfs(nums, 0, [], lists)
  8. return lists
  9. }
  10. let dfs = function (nums, index, list, lists) {
  11. if (index === nums.length) {
  12. lists.push([...list])
  13. return
  14. }
  15. dfs(nums, index + 1, list, lists)
  16. list.push(nums[index])
  17. dfs(nums, index + 1, list, lists)
  18. list.pop()
  19. }

位运算

  1. /**
  2. * @param {number[]} nums
  3. * @return {number[][]}
  4. */
  5. var subsets = function (nums) {
  6. let lists = []
  7. let count = 1 << nums.length
  8. for (let i = 0; i < count; i++) {
  9. let list = []
  10. for (let j = 0; j < nums.length; j++) {
  11. if (i & (1 << j)) {
  12. list.push(nums[j])
  13. }
  14. }
  15. lists.push([...list])
  16. }
  17. return lists
  18. }

迭代

  1. /**
  2. * @param {number[]} nums
  3. * @return {number[][]}
  4. */
  5. var subsets = function (nums) {
  6. let lists = [[]]
  7. for (let i = 0; i < nums.length; i++) {
  8. let size = lists.length
  9. for (let j = 0; j < size; j++) {
  10. lists.push(lists[j].concat(nums[i]))
  11. }
  12. }
  13. return lists
  14. }