Skip to content

Commit 349714e

Browse files
committed
Add solution #216
1 parent f7c0b82 commit 349714e

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,7 @@
151151
213|[House Robber II](./0213-house-robber-ii.js)|Medium|
152152
214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard|
153153
215|[Kth Largest Element in an Array](./0215-kth-largest-element-in-an-array.js)|Medium|
154+
216|[Combination Sum III](./0216-combination-sum-iii.js)|Medium|
154155
217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy|
155156
219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy|
156157
225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy|

solutions/0216-combination-sum-iii.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* 216. Combination Sum III
3+
* https://leetcode.com/problems/combination-sum-iii/
4+
* Difficulty: Medium
5+
*
6+
* Find all valid combinations of k numbers that sum up to n such that the following
7+
* conditions are true:
8+
* - Only numbers 1 through 9 are used.
9+
* - Each number is used at most once.
10+
*
11+
* Return a list of all possible valid combinations. The list must not contain the same
12+
* combination twice, and the combinations may be returned in any order.
13+
*/
14+
15+
/**
16+
* @param {number} k
17+
* @param {number} n
18+
* @return {number[][]}
19+
*/
20+
var combinationSum3 = function(k, n) {
21+
const result = [];
22+
23+
function backtrack(history, sum, start) {
24+
if (sum > n) return;
25+
if (history.length === k && sum === n) {
26+
result.push(history);
27+
return;
28+
}
29+
for (let i = start; i < 10; i++) {
30+
backtrack([...history, i], sum + i, i + 1);
31+
}
32+
}
33+
34+
backtrack([], 0, 1);
35+
36+
return result;
37+
};

0 commit comments

Comments
 (0)