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

组合总和 II #22

Open
Mooo-star opened this issue Jul 4, 2024 · 1 comment
Open

组合总和 II #22

Mooo-star opened this issue Jul 4, 2024 · 1 comment
Labels
回溯 回溯算法 算法 记录算法

Comments

@Mooo-star
Copy link
Owner

给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用 一次 。

注意:解集不能包含重复的组合。

示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]

@Mooo-star Mooo-star added 回溯 回溯算法 算法 记录算法 labels Jul 4, 2024
@Mooo-star
Copy link
Owner Author

/**
 * @param {number[]} candidates
 * @param {number} target
 * @return {number[][]}
 */
var combinationSum2 = function (candidates, target) {
    const result = [];
    const len = candidates.length
    candidates = candidates.sort((a, b) => a - b)

    function backtrack(startIndex, path, sum) {

        if (sum === target) {
            result.push(path)
            return
        }

        for (let i = startIndex; i < len; i++) {
            const num = candidates[i]

            if(i > startIndex && num === candidates[i-1]){
                continue
            }

            if (num + sum > target) {
                return
            }

            backtrack(i + 1, [...path, num], sum + num)
        }
    }

    backtrack(0, [], 0, )

    return result
};

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