Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit49bd1fd

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 parentc40e4cf commit49bd1fd

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

‎Backtracking/generateParentheses.js

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)

[8]ページ先頭

©2009-2025 Movatter.jp