Skip to content

Commit 49bd1fd

Browse files
authored
Adding to backtracking (TheAlgorithms#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
Lines changed: 31 additions & 0 deletions
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+
constgenerateParentheses=(n)=>{
9+
constres=[]
10+
11+
constsolve=(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+
returnres
29+
}
30+
31+
export{generateParentheses}
Lines changed: 5 additions & 0 deletions
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)