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

Commit 14cffa1

Browse files
Add solution to 22.
1 parent 2087f24 commit 14cffa1

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @param {number} n
3+
* @return {string[]}
4+
*/
5+
var generateParenthesis = function (n) {
6+
const stack = [];
7+
const out = [];
8+
9+
backtrack(0, 0, n, stack, out);
10+
11+
return out;
12+
};
13+
14+
const backtrack = function (opened, closed, n, stack, out) {
15+
if (opened === n && closed === n) {
16+
out.push(stack.join(""));
17+
return;
18+
}
19+
20+
if (opened < n) {
21+
stack.push("(");
22+
backtrack(opened + 1, closed, n, stack, out);
23+
stack.pop();
24+
}
25+
26+
if (closed < opened) {
27+
stack.push(")");
28+
backtrack(opened, closed + 1, n, stack, out);
29+
stack.pop();
30+
}
31+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /