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

子集-78 #71

Open
sl1673495 opened this issue Jun 11, 2020 · 0 comments
Open

子集-78 #71

sl1673495 opened this issue Jun 11, 2020 · 0 comments
Labels
待复习 看题解或者做出来很艰难的,需要回顾。 递归与回溯

Comments

@sl1673495
Copy link
Owner

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

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

示例:

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

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

思路

求子集,其实可以转化为在数组中,求长度从 1 ~ nums.length 的每种长度下的全部组合。

那么定义 helper 函数,接受的参数为 start 起点, prev 之前拼成的数组,targetLength 目标长度。在这个递归过程中,目标长度是不变的。只需要 prev 的长度和 targetLength 相等,即可完成一个结果放入 res 数组中。

最后,针对 targetLength1 ~ nums.length ,分别调用 helper 函数即可:

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
let subsets = function (nums) {
  let res = []
  let n = nums.length
  if (n === 0) {
    return res
  }

  let helper = (start, prev, targetLength) => {
    if (start > n) {
      return
    }
    if (prev.length === targetLength) {
      res.push(prev)
      return
    }

    for (let i = start; i < n; i++) {
      let cur = nums[i]
      helper(i + 1, prev.concat(cur), targetLength)
    }
  }

  for (let j = 1; j <= nums.length; j++) {
    helper(0, [], j)
  }

  return [[], ...res]
}
@sl1673495 sl1673495 added 待复习 看题解或者做出来很艰难的,需要回顾。 递归与回溯 labels Jun 11, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
待复习 看题解或者做出来很艰难的,需要回顾。 递归与回溯
Projects
None yet
Development

No branches or pull requests

1 participant