Skip to content

Commit 49bd1fd

Browse files
authoredFeb 13, 2023
Adding to backtracking (#1289)
* adding generate-parenthses algorithm * adding generateParenthses algorithm * adding generate parentheses algorithm * fixing comments according to the JDoc comments, cleaning code * fixing comments
1 parent c40e4cf commit 49bd1fd

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
 

Diff for: ‎Backtracking/generateParentheses.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Problem Statement: Given a number n pairs of parentheses, try to Generate all combinations of valid parentheses;
3+
* @param {number} n - number of given parentheses
4+
* @return {string[]} res - array that contains all valid parentheses
5+
* @see https://leetcode.com/problems/generate-parentheses/
6+
*/
7+
8+
const generateParentheses = (n) => {
9+
const res = []
10+
11+
const solve = (chres, openParenthese, closedParenthese) => {
12+
if (openParenthese === n && closedParenthese === n) {
13+
res.push(chres)
14+
return
15+
}
16+
17+
if (openParenthese <= n) {
18+
solve(chres + '(', openParenthese + 1, closedParenthese)
19+
}
20+
21+
if (closedParenthese < openParenthese) {
22+
solve(chres + ')', openParenthese, closedParenthese + 1)
23+
}
24+
}
25+
26+
solve('', 0, 0)
27+
28+
return res
29+
}
30+
31+
export { generateParentheses }

Diff for: ‎Backtracking/tests/GenerateParentheses.test.js

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import { generateParentheses } from '../generateParentheses'
2+
3+
test('generate all valid parentheses of input 3', () => {
4+
expect(generateParentheses(3)).toStrictEqual(['((()))', '(()())', '(())()', '()(())', '()()()'])
5+
})

0 commit comments

Comments
 (0)
Please sign in to comment.