Skip to content

子集 #33

Open
Open

Description

@louzhedong

习题

出处:LeetCode 算法第78题

给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

**说明:**解集不能包含重复的子集。

示例:

输入: nums = [1,2,3]
输出:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

思路

还是采用深度递归遍历的算法,枚举所有可能性

解答

var subsets = function (nums) {
  var result = [];
  var temp = [];
  DFS(result, temp, -1, nums);
  return result;
};

function DFS(result, temp, index, nums) {
  if (index <= nums.length) {
    result.push(copy(temp));
    for (var i = index + 1; i < nums.length; i++) {
      temp.push(nums[i]);
      DFS(result, temp, i, nums);
      temp.pop();
    }
  }
}

function copy(array) {
  var res = [];
  for (var i = 0, len = array.length; i < len; i++) {
    res.push(array[i]);
  }
  return res;
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions