-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChapter2-Typescript.ts
42 lines (32 loc) · 1019 Bytes
/
Chapter2-Typescript.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Given a number n pairs of parentheses, generate all combinations of valid parentheses
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
* @param {number} n: Number of given parentheses
* @return {string[]} result: Array that contains all valid parentheses
* @see https://leetcode.com/problems/generate-parentheses/
*
*/
const generateParentheses = (n: number): string[] => {
const result: string[] = []
const solve = (
chars: string,
openParentheses: number,
closedParentheses: number
) => {
if (openParentheses === n && closedParentheses === n) {
result.push(chars)
return
}
if (openParentheses <= n) {
solve(chars + '(', openParentheses + 1, closedParentheses)
}
if (closedParentheses < openParentheses) {
solve(chars + ')', openParentheses, closedParentheses + 1)
}
}
solve('', 0, 0)
return result
}
console.log( generateParentheses(3))