Skip to content

Commit ca21982

Browse files
authored
feat: add typescript solution to lc problem: No.0022.Generate Parentheses (doocs#489)
1 parent 2ad2437 commit ca21982

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed

solution/0000-0099/0022.Generate Parentheses/README.md

+25
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@
3737

3838
<!-- 这里可写通用的实现逻辑 -->
3939

40+
dfs
41+
4042
<!-- tabs:start -->
4143

4244
### **Python3**
@@ -87,6 +89,29 @@ class Solution {
8789
}
8890
```
8991

92+
### **TypeScript**
93+
94+
```ts
95+
function generateParenthesis(n: number): string[] {
96+
let ans = [];
97+
dfs(n, 0, 0, '', ans);
98+
return ans;
99+
};
100+
101+
function dfs(n: number, left: number, right: number, str: string, ans: string[]) {
102+
if (str.length == 2 * n) {
103+
ans.push(str);
104+
return;
105+
}
106+
if (left < n) {
107+
dfs(n, left + 1, right, str + '(', ans);
108+
}
109+
if (right < left) {
110+
dfs(n, left, right + 1, str + ')', ans);
111+
}
112+
}
113+
```
114+
90115
### **C++**
91116

92117
```cpp

solution/0000-0099/0022.Generate Parentheses/README_EN.md

+23
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,29 @@ class Solution {
7070
}
7171
```
7272

73+
### **TypeScript**
74+
75+
```ts
76+
function generateParenthesis(n: number): string[] {
77+
let ans = [];
78+
dfs(n, 0, 0, '', ans);
79+
return ans;
80+
};
81+
82+
function dfs(n: number, left: number, right: number, str: string, ans: string[]) {
83+
if (str.length == 2 * n) {
84+
ans.push(str);
85+
return;
86+
}
87+
if (left < n) {
88+
dfs(n, left + 1, right, str + '(', ans);
89+
}
90+
if (right < left) {
91+
dfs(n, left, right + 1, str + ')', ans);
92+
}
93+
}
94+
```
95+
7396
### **C++**
7497

7598
```cpp
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
function generateParenthesis(n: number): string[] {
2+
let ans = [];
3+
dfs(n, 0, 0, '', ans);
4+
return ans;
5+
};
6+
7+
function dfs(n: number, left: number, right: number, str: string, ans: string[]) {
8+
if (str.length == 2 * n) {
9+
ans.push(str);
10+
return;
11+
}
12+
if (left < n) {
13+
dfs(n, left + 1, right, str + '(', ans);
14+
}
15+
if (right < left) {
16+
dfs(n, left, right + 1, str + ')', ans);
17+
}
18+
}

0 commit comments

Comments
 (0)