Skip to content

78. 子集 #34

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

Open
Geekhyt opened this issue Feb 14, 2021 · 0 comments
Open

78. 子集 #34

Geekhyt opened this issue Feb 14, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Feb 14, 2021

原题链接

回溯

你爱,或者不爱我。爱就在那里,不增不减。

  1. 对于数组中的每个元素都有两种选择:选或者不选。
  2. 对于当前迭代的元素,选择它就将其 push 后,基于选择后的状态从 start + 1 递归。
  3. 然后使用 pop 将其状态恢复,不选择当前迭代的元素从 start + 1 递归。
const subsets = function(nums) => {
    const res = []
    const dfs = function(start, cur) {
        if (start === nums.length) {
            res.push(cur.slice())
            return
        }
        cur.push(nums[start]) // 选择
        dfs(start + 1, cur)
        cur.pop()
        dfs(start + 1, cur) // 不选择
    }
    dfs(0, [])
    return res
}
  • 时间复杂度: O(n * 2^n),共 2^n 个状态,需要 O(n) 的时间来构造子集。
  • 空间复杂度: O(n)
@Geekhyt Geekhyt added the 中等 label Jun 2, 2021
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