Skip to content

Commit 1460488

Browse files
committed
Add solution #22
1 parent 32ff5b3 commit 1460488

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
19|[Remove Nth Node From End of List](./0019-remove-nth-node-from-end-of-list.js)|Medium|
2525
20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy|
2626
21|[Merge Two Sorted Lists](./0021-merge-two-sorted-lists.js)|Easy|
27+
22|[Generate Parentheses](./0022-generate-parentheses.js)|Medium|
2728
27|[Remove Element](./0027-remove-element.js)|Easy|
2829
28|[Implement strStr()](./0028-implement-strstr.js)|Easy|
2930
31|[Next Permutation](./0031-next-permutation.js)|Medium|
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* 22. Generate Parentheses
3+
* https://leetcode.com/problems/generate-parentheses/
4+
* Difficulty: Medium
5+
*
6+
* Given n pairs of parentheses, write a function to generate all combinations of
7+
* well-formed parentheses.
8+
*/
9+
10+
/**
11+
* @param {number} n
12+
* @return {string[]}
13+
*/
14+
var generateParenthesis = function(n) {
15+
const result = [];
16+
backtrack(result, '', 0, 0, n);
17+
return result;
18+
};
19+
20+
function backtrack(result, str, open, close, max) {
21+
if (str.length == max * 2){
22+
result.push(str);
23+
return;
24+
}
25+
26+
if (open < max) backtrack(result, `${str}(`, open + 1, close, max);
27+
if (close < open) backtrack(result, `${str})`, open, close + 1, max);
28+
}

0 commit comments

Comments
 (0)