-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path22.generate-parentheses.java
More file actions
57 lines (55 loc) · 1.19 KB
/
22.generate-parentheses.java
File metadata and controls
57 lines (55 loc) · 1.19 KB
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
53
54
55
56
/*
* @lc app=leetcode id=22 lang=java
*
* [22] Generate Parentheses
*
* https://leetcode.com/problems/generate-parentheses/description/
*
* algorithms
* Medium (56.17%)
* Likes: 3055
* Dislikes: 190
* Total Accepted: 370.5K
* Total Submissions: 659.1K
* 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:
*
*
* [
* "((()))",
* "(()())",
* "(())()",
* "()(())",
* "()()()"
* ]
*
*/
class Solution {
public List<String> generateParenthesis(int n) {
if (n == 0) {
return Collections.emptyList();
}
List<String> res = new ArrayList<>();
backtrack(res, "", n, 0, 0);
return res;
}
private void backtrack(List<String> res, String cur, int n, int left, int right) {
if (cur.length() == n * 2) {
res.add(cur);
return;
}
if (left < n) {
backtrack(res, cur + "(", n, left + 1, right);
}
if (right < left) {
backtrack(res, cur + ")", n, left, right + 1);
}
}
}