Skip to content

Commit ecd4666

Browse files
committed
22. Generate Parentheses
```Solution.c /** * Note: The returned array must be malloced, assume caller calls free(). */ void backtrack(char **result, char *current, int open, int close, int n, int *count) { if (open == n && close == n) { current[open + close] = '\0'; result[*count] = (char *)malloc((2 * n + 1) * sizeof(char)); strcpy(result[*count], current); (*count)++; return; } if (open < n) { current[open + close] = '('; backtrack(result, current, open + 1, close, n, count); } if (close < open) { current[open + close] = ')'; backtrack(result, current, open, close + 1, n, count); } } char** generateParenthesis(int n, int* returnSize) { int maxSize = 1; for (int i = 0; i < n; ++i) { maxSize = maxSize * 2 * (2 * i + 1) / (i + 2); } char **result = (char **)malloc(maxSize * sizeof(char *)); char *current = (char *)malloc((2 * n + 1) * sizeof(char)); current[2 * n] = '\0'; int count = 0; backtrack(result, current, 0, 0, n, &count); free(current); *returnSize = count; return result; } ``` ```Solution.cpp class Solution { public: vector<string> generateParenthesis(int n) { vector<string> result; function<void(string, int, int)> backtrack = [&](string curr, int open, int close) { if (curr.size() == n * 2) { result.push_back(curr); return; } if (open < n) backtrack(curr + '(', open + 1, close); if (close < open) backtrack(curr + ')', open, close + 1); }; backtrack("", 0, 0); return result; } }; ``` ```Solution.cs public class Solution { public IList<string> GenerateParenthesis(int n) { IList<string> result = new List<string>(); char[] current = new char[2 * n]; backtrack(result, current, 0, 0, n); return result; } private void backtrack(IList<string> result, char[] current, int open, int close, int n) { if (open == n && close == n) { result.Add(new string(current)); return; } if (open < n) { current[open + close] = '('; backtrack(result, current, open + 1, close, n); } if (close < open) { current[open + close] = ')'; backtrack(result, current, open, close + 1, n); } } } ``` ```Solution.dart class Solution { List<String> generateParenthesis(int n) { List<String> result = []; void backtrack(String current, int open, int close) { if (current.length == n * 2) { result.add(current); return; } if (open < n) { backtrack(current + '(', open + 1, close); } if (close < open) { backtrack(current + ')', open, close + 1); } } backtrack('', 0, 0); return result; } } ``` ```Solution.erl -spec generate_parenthesis(N :: integer()) -> [unicode:unicode_binary()]. generate_parenthesis(N) -> generate(N, N, <<>>). generate(0, 0, Acc) -> [Acc]; generate(Open, Close, Acc) when Open > 0, Open =< Close -> generate(Open - 1, Close, <<Acc/binary, "(">>) ++ (if Close > Open -> generate(Open, Close - 1, <<Acc/binary, ")">>); true -> [] end); generate(Open, Close, Acc) when Close > Open -> generate(Open, Close - 1, <<Acc/binary, ")">>); generate(_, _, _) -> []. ``` ```Solution.ex defmodule Solution do @SPEC generate_parenthesis(n :: integer) :: [String.t] def generate_parenthesis(n) do generate([], "", 0, 0, n) end defp generate(acc, curr, open, close, n) do if String.length(curr) == n * 2 do [curr | acc] else acc = if open < n do generate(acc, curr <> "(", open + 1, close, n) else acc end if close < open do generate(acc, curr <> ")", open, close + 1, n) else acc end end end end ``` ```Solution.go func generateParenthesis(n int) []string { var res []string var backtrack func(s string, left, right int) backtrack = func(s string, left, right int) { if len(s) == 2*n { res = append(res, s) return } if left < n { backtrack(s+"(", left+1, right) } if right < left { backtrack(s+")", left, right+1) } } backtrack("", 0, 0) return res } ``` ```Solution.java class Solution { public List<String> generateParenthesis(int n) { List<String> result = new ArrayList<>(); backtrack(result, "", 0, 0, n); return result; } private void backtrack(List<String> result, String current, int open, int close, int max) { if (current.length() == max * 2) { result.add(current); return; } if (open < max) { backtrack(result, current + "(", open + 1, close, max); } if (close < open) { backtrack(result, current + ")", open, close + 1, max); } } } ``` ```Solution.js /** * @param {number} n * @return {string[]} */ var generateParenthesis = function(n) { var result = []; var backtrack = function(current, open, close) { if (current.length === n * 2) { result.push(current); return; } if (open < n) { backtrack(current + '(', open + 1, close); } if (close < open) { backtrack(current + ')', open, close + 1); } }; backtrack('', 0, 0); return result; }; ``` ```Solution.kt class Solution { fun generateParenthesis(n: Int): List<String> { val result = mutableListOf<String>() fun backtrack(current: String, open: Int, close: Int) { if (current.length == n * 2) { result.add(current) return } if (open < n) { backtrack(current + "(", open + 1, close) } if (close < open) { backtrack(current + ")", open, close + 1) } } backtrack("", 0, 0) return result } } ``` ```Solution.php class Solution { /** * @param Integer $n * @return String[] */ function generateParenthesis($n) { $result = []; $this->backtrack($result, "", 0, 0, $n); return $result; } private function backtrack(&$result, $current, $open, $close, $max) { if (strlen($current) == $max * 2) { $result[] = $current; return; } if ($open < $max) { $this->backtrack($result, $current . "(", $open + 1, $close, $max); } if ($close < $open) { $this->backtrack($result, $current . ")", $open, $close + 1, $max); } } } ``` ```Solution.py class Solution: def generateParenthesis(self, n: int) -> List[str]: result = [] self.backtrack(result, "", 0, 0, n) return result def backtrack(self, result, current, open, close, max): if len(current) == max * 2: result.append(current) return if open < max: self.backtrack(result, current + "(", open + 1, close, max) if close < open: self.backtrack(result, current + ")", open, close + 1, max) ``` ```Solution.rb # @param {Integer} n # @return {String[]} def generate_parenthesis(n) result = [] backtrack(result, "", 0, 0, n) return result end def backtrack(result, current, open, close, max) if current.length == max * 2 result << current return end if open < max backtrack(result, current + "(", open + 1, close, max) end if close < open backtrack(result, current + ")", open, close + 1, max) end end ``` ```Solution.rkt (define/contract (generate-parenthesis n) (-> exact-integer? (listof string?)) (define (loop left right s) (cond [(and (= left 0) (= right 0)) (list s)] [else (append (if (> left 0) (loop (- left 1) right (string-append s "(")) '()) (if (> right left) (loop left (- right 1) (string-append s ")")) '()))])) (loop n n "") ) ``` ```Solution.rs impl Solution { pub fn generate_parenthesis(n: i32) -> Vec<String> { let mut result = Vec::new(); Self::backtrack(&mut result, String::new(), 0, 0, n); result } fn backtrack(result: &mut Vec<String>, current: String, open: i32, close: i32, max: i32) { if current.len() == (max * 2) as usize { result.push(current); return; } if open < max { Self::backtrack(result, format!("{}(", current), open + 1, close, max); } if close < open { Self::backtrack(result, format!("{}{}", current, ")"), open, close + 1, max); } } } ``` ```Solution.scala object Solution { def generateParenthesis(n: Int): List[String] = { def backtrack(s: String, left: Int, right: Int): List[String] = { if (s.length == n * 2) List(s) else { val addLeft = if (left < n) backtrack(s + "(", left + 1, right) else Nil val addRight = if (right < left) backtrack(s + ")", left, right + 1) else Nil addLeft ++ addRight } } backtrack("", 0, 0) } } ``` ```Solution.swift class Solution { func generateParenthesis(_ n: Int) -> [String] { var result = [String]() backtrack(&result, "", 0, 0, n) return result } private func backtrack(_ result: inout [String], _ current: String, _ open: Int, _ close: Int, _ max: Int) { if current.count == max * 2 { result.append(current) return } if open < max { backtrack(&result, current + "(", open + 1, close, max) } if close < open { backtrack(&result, current + ")", open, close + 1, max) } } } ``` ```Solution.ts function generateParenthesis(n: number): string[] { const res: string[] = []; if (n === 0) return res; function generate(openN: number, closeN: number, path: string) { if (path.length === n * 2) { res.push(path); return; } if (openN < n) { generate(openN + 1, closeN, path + "("); } if (closeN < openN) { generate(openN, closeN + 1, path + ")"); } } generate(0, 0, ""); return res; }; ```
1 parent 84cf55a commit ecd4666

19 files changed

+363
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# [**22. Generate Parentheses**](https://leetcode.com/problems/generate-parentheses/description/)
2+
3+
Given `n` pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
4+
5+
#### **Example 1:**
6+
7+
```md
8+
Input: n = 3
9+
Output: ["((()))","(()())","(())()","()(())","()()()"]
10+
```
11+
12+
#### **Example 2:**
13+
```md
14+
Input: n = 1
15+
Output: ["()"]
16+
```
17+
18+
#### **Constraints:**
19+
> - `1 <= n <= 8`
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Note: The returned array must be malloced, assume caller calls free().
3+
*/
4+
void backtrack(char **result, char *current, int open, int close, int n, int *count) {
5+
if (open == n && close == n) {
6+
current[open + close] = '\0';
7+
result[*count] = (char *)malloc((2 * n + 1) * sizeof(char));
8+
strcpy(result[*count], current);
9+
(*count)++;
10+
return;
11+
}
12+
if (open < n) {
13+
current[open + close] = '(';
14+
backtrack(result, current, open + 1, close, n, count);
15+
}
16+
if (close < open) {
17+
current[open + close] = ')';
18+
backtrack(result, current, open, close + 1, n, count);
19+
}
20+
}
21+
char** generateParenthesis(int n, int* returnSize) {
22+
int maxSize = 1;
23+
for (int i = 0; i < n; ++i) {
24+
maxSize = maxSize * 2 * (2 * i + 1) / (i + 2);
25+
}
26+
char **result = (char **)malloc(maxSize * sizeof(char *));
27+
char *current = (char *)malloc((2 * n + 1) * sizeof(char));
28+
current[2 * n] = '\0';
29+
int count = 0;
30+
backtrack(result, current, 0, 0, n, &count);
31+
free(current);
32+
*returnSize = count;
33+
return result;
34+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public:
3+
vector<string> generateParenthesis(int n) {
4+
vector<string> result;
5+
function<void(string, int, int)> backtrack = [&](string curr, int open, int close) {
6+
if (curr.size() == n * 2) {
7+
result.push_back(curr);
8+
return;
9+
}
10+
if (open < n)
11+
backtrack(curr + '(', open + 1, close);
12+
if (close < open)
13+
backtrack(curr + ')', open, close + 1);
14+
};
15+
backtrack("", 0, 0);
16+
return result;
17+
}
18+
};
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
public class Solution {
2+
public IList<string> GenerateParenthesis(int n) {
3+
IList<string> result = new List<string>();
4+
char[] current = new char[2 * n];
5+
backtrack(result, current, 0, 0, n);
6+
return result;
7+
}
8+
private void backtrack(IList<string> result, char[] current, int open, int close, int n) {
9+
if (open == n && close == n) {
10+
result.Add(new string(current));
11+
return;
12+
}
13+
if (open < n) {
14+
current[open + close] = '(';
15+
backtrack(result, current, open + 1, close, n);
16+
}
17+
if (close < open) {
18+
current[open + close] = ')';
19+
backtrack(result, current, open, close + 1, n);
20+
}
21+
}
22+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
List<String> generateParenthesis(int n) {
3+
List<String> result = [];
4+
void backtrack(String current, int open, int close) {
5+
if (current.length == n * 2) {
6+
result.add(current);
7+
return;
8+
}
9+
if (open < n) {
10+
backtrack(current + '(', open + 1, close);
11+
}
12+
if (close < open) {
13+
backtrack(current + ')', open, close + 1);
14+
}
15+
}
16+
backtrack('', 0, 0);
17+
return result;
18+
}
19+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
-spec generate_parenthesis(N :: integer()) -> [unicode:unicode_binary()].
2+
generate_parenthesis(N) ->
3+
generate(N, N, <<>>).
4+
generate(0, 0, Acc) ->
5+
[Acc];
6+
generate(Open, Close, Acc) when Open > 0, Open =< Close ->
7+
generate(Open - 1, Close, <<Acc/binary, "(">>) ++
8+
(if Close > Open -> generate(Open, Close - 1, <<Acc/binary, ")">>); true -> [] end);
9+
generate(Open, Close, Acc) when Close > Open ->
10+
generate(Open, Close - 1, <<Acc/binary, ")">>);
11+
generate(_, _, _) ->
12+
[].
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
defmodule Solution do
2+
@spec generate_parenthesis(n :: integer) :: [String.t]
3+
def generate_parenthesis(n) do
4+
generate([], "", 0, 0, n)
5+
end
6+
defp generate(acc, curr, open, close, n) do
7+
if String.length(curr) == n * 2 do
8+
[curr | acc]
9+
else
10+
acc =
11+
if open < n do
12+
generate(acc, curr <> "(", open + 1, close, n)
13+
else
14+
acc
15+
end
16+
if close < open do
17+
generate(acc, curr <> ")", open, close + 1, n)
18+
else
19+
acc
20+
end
21+
end
22+
end
23+
end
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
func generateParenthesis(n int) []string {
2+
var res []string
3+
var backtrack func(s string, left, right int)
4+
backtrack = func(s string, left, right int) {
5+
if len(s) == 2*n {
6+
res = append(res, s)
7+
return
8+
}
9+
if left < n {
10+
backtrack(s+"(", left+1, right)
11+
}
12+
if right < left {
13+
backtrack(s+")", left, right+1)
14+
}
15+
}
16+
backtrack("", 0, 0)
17+
return res
18+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
public List<String> generateParenthesis(int n) {
3+
List<String> result = new ArrayList<>();
4+
backtrack(result, "", 0, 0, n);
5+
return result;
6+
}
7+
private void backtrack(List<String> result, String current, int open, int close, int max) {
8+
if (current.length() == max * 2) {
9+
result.add(current);
10+
return;
11+
}
12+
if (open < max) {
13+
backtrack(result, current + "(", open + 1, close, max);
14+
}
15+
if (close < open) {
16+
backtrack(result, current + ")", open, close + 1, max);
17+
}
18+
}
19+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* @param {number} n
3+
* @return {string[]}
4+
*/
5+
var generateParenthesis = function(n) {
6+
var result = [];
7+
var backtrack = function(current, open, close) {
8+
if (current.length === n * 2) {
9+
result.push(current);
10+
return;
11+
}
12+
if (open < n) {
13+
backtrack(current + '(', open + 1, close);
14+
}
15+
if (close < open) {
16+
backtrack(current + ')', open, close + 1);
17+
}
18+
};
19+
backtrack('', 0, 0);
20+
return result;
21+
};

0 commit comments

Comments
 (0)