Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 264b661

Browse files
committedJan 15, 2022
Add solution #39
1 parent e69f7df commit 264b661

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
34|[Find First and Last Position of Element in Sorted Array](./0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium|
4040
35|[Search Insert Position](./0035-search-insert-position.js)|Easy|
4141
36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium|
42+
39|[Combination Sum](./0039-combination-sum.js)|Medium|
4243
41|[First Missing Positive](./0041-first-missing-positive.js)|Hard|
4344
42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard|
4445
43|[Multiply Strings](./0043-multiply-strings.js)|Medium|

‎solutions/0039-combination-sum.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* 39. Combination Sum
3+
* https://leetcode.com/problems/combination-sum/
4+
* Difficulty: Medium
5+
*
6+
* Given an array of distinct integers candidates and a target integer target,
7+
* return a list of all unique combinations of candidates where the chosen
8+
* numbers sum to target. You may return the combinations in any order.
9+
*
10+
* The same number may be chosen from candidates an unlimited number of times.
11+
* Two combinations are unique if the frequency of at least one of the chosen
12+
* numbers is different.
13+
*
14+
* It is guaranteed that the number of unique combinations that sum up to target
15+
* is less than 150 combinations for the given input.
16+
*/
17+
18+
/**
19+
* @param {number[]} candidates
20+
* @param {number} target
21+
* @return {number[][]}
22+
*/
23+
var combinationSum = function(candidates, target) {
24+
const result = [];
25+
backtrack(result, candidates, target);
26+
return result;
27+
};
28+
29+
function backtrack(result, candidates, target, combination = [], offset = 0) {
30+
if (target < 0) {
31+
return;
32+
} else if (target === 0) {
33+
result.push(combination);
34+
} else {
35+
for (let i = offset; i < candidates.length; i++) {
36+
backtrack(result, candidates, target - candidates[i], [...combination, candidates[i]], i);
37+
}
38+
}
39+
}

0 commit comments

Comments
 (0)
Please sign in to comment.