Skip to content

Commit e69f7df

Browse files
committed
Add solution #77
1 parent a049739 commit e69f7df

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@
5353
67|[Add Binary](./0067-add-binary.js)|Easy|
5454
73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium|
5555
74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium|
56+
77|[Combinations](./0077-combinations.js)|Medium|
5657
83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy|
5758
88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy|
5859
94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy|

solutions/0077-combinations.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* 77. Combinations
3+
* https://leetcode.com/problems/combinations/
4+
* Difficulty: Medium
5+
*
6+
* Given two integers n and k, return all possible combinations of k numbers
7+
* out of the range [1, n].
8+
*
9+
* You may return the answer in any order.
10+
*/
11+
12+
/**
13+
* @param {number} n
14+
* @param {number} k
15+
* @return {number[][]}
16+
*/
17+
var combine = function(n, k) {
18+
const result = [];
19+
backtrack(result, n, k);
20+
return result;
21+
};
22+
23+
function backtrack(result, n, k, combination = [], offset = 1) {
24+
if (combination.length === k) {
25+
result.push(combination);
26+
} else {
27+
while (offset <= n) {
28+
backtrack(result, n, k, [...combination, offset], ++offset);
29+
}
30+
}
31+
}

0 commit comments

Comments
 (0)