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

39. 组合总和 #30

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

39. 组合总和 #30

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

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Feb 9, 2021

原题链接

回溯

先明确,元素可以重复使用,但是组合不能重复。

  1. 使用回溯法,不符合条件的情况进行剪枝。
  2. cur === target 时,拷贝 arr 推进结果集。
  3. 从 start 开始遍历可选数组,选择当前数字后递归时注意要基于当前状态 i 继续选择,因为元素是可以重复进入集合的。
  4. 撤销选择,恢复状态。
const combinationSum = (candidates, target) => {
    const res = []
    // start: 起点索引 arr: 当前集合 cur: 当前所求之和
    const dfs = (start, arr, cur) => {
        if (cur > target) return
        if (cur === target) {
            res.push(arr.slice())
            return
        }
        for (let i = start; i < candidates.length; i++) {
            arr.push(candidates[i])
            dfs(i, arr, cur + candidates[i])
            arr.pop()
        }
    }
    dfs(0, [], 0)
    return res
}
@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