-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy path22.generate-parentheses.go
52 lines (49 loc) · 1.03 KB
/
22.generate-parentheses.go
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
43
44
45
46
47
48
49
50
51
52
/*
* @lc app=leetcode id=22 lang=golang
*
* [22] Generate Parentheses
*
* https://leetcode.com/problems/generate-parentheses/description/
*
* algorithms
* Medium (52.61%)
* Total Accepted: 291.7K
* Total Submissions: 554.2K
* Testcase Example: '3'
*
*
* Given n pairs of parentheses, write a function to generate all combinations
* of well-formed parentheses.
*
*
*
* For example, given n = 3, a solution set is:
*
*
* [
* "((()))",
* "(()())",
* "(())()",
* "()(())",
* "()()()"
* ]
*
*/
func generateParenthesis(n int) []string {
ans := []string{}
parentheses(n, n, []byte{}, &ans)
return ans
}
func parentheses(left, right int, p []byte, ans *[]string) {
// Valid well-formed parentheses:
// Remaining left count cannot bigger than remaining right count.
if left > right || left < 0 || right < 0 {
return
}
if left == 0 && right == 0 {
*ans = append(*ans, string(p))
return
}
parentheses(left-1, right, append(p, '('), ans)
parentheses(left, right-1, append(p, ')'), ans)
}