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. Combination Sum #321

Open
Tcdian opened this issue Sep 9, 2020 · 1 comment
Open

39. Combination Sum #321

Tcdian opened this issue Sep 9, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented Sep 9, 2020

39. Combination Sum

给定一个 无重复元素 的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

Note

  • 所有数字(包括 target)都是正整数。
  • 解集不能包含重复的组合。

Example 1

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

Constraints

  • 1 <= candidates.length <= 30
  • 1 <= candidates[i] <= 200
  • candidate 中的每个元素都是独一无二的。
  • 1 <= target <= 500
@Tcdian
Copy link
Owner Author

Tcdian commented Sep 9, 2020

Solution

  • JavaScript Solution
/**
 * @param {number[]} candidates
 * @param {number} target
 * @return {number[][]}
 */
var combinationSum = function(candidates, target) {
    candidates.sort((a, b) => a - b);
    const reuslt = [];
    const part = [];
    backtracking(0);
    return reuslt;

    function backtracking(index) {
        const sum = part.reduce((prev, current) => prev + current, 0);
        if (sum >= target) {
            if (sum === target) {
                reuslt.push([...part]);
            }
            return;
        }
        for (let i = index; i < candidates.length; i++) {
            part.push(candidates[i]);
            backtracking(i);
            part.pop();
        }
    }
};
  • TypeScript Solution
function combinationSum(candidates: number[], target: number): number[][] {
    candidates.sort((a, b) => a - b);
    const reuslt: number[][] = [];
    const part: number[] = [];
    backtracking(0);
    return reuslt;

    function backtracking(index: number) {
        const sum = part.reduce((prev, current) => prev + current, 0);
        if (sum >= target) {
            if (sum === target) {
                reuslt.push([...part]);
            }
            return;
        }
        for (let i = index; i < candidates.length; i++) {
            part.push(candidates[i]);
            backtracking(i);
            part.pop();
        }
    }
};

@Tcdian Tcdian removed the Classic label Jul 30, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant