Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

子集 #33

Open
louzhedong opened this issue Jun 14, 2018 · 0 comments
Open

子集 #33

louzhedong opened this issue Jun 14, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处: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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant