forked from leetcoders/LeetCode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GenerateParentheses.java
30 lines (28 loc) · 1.04 KB
/
GenerateParentheses.java
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
/*
Author: King, [email protected]
Date: Dec 20, 2014
Problem: Generate Parentheses
Difficulty: Medium
Source: https://oj.leetcode.com/problems/generate-parentheses/
Notes:
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Solution: Place n left '(' and n right ')'.
Cannot place ')' if there are no enough matching '('.
*/
public class Solution {
public List<String> generateParenthesis(int n) {
ArrayList<String> res = new ArrayList<String>();
generateParenthesisRe(res, n, n, "");
return res;
}
public void generateParenthesisRe(ArrayList<String> res, int left, int right, String s) {
if (left == 0 && right == 0)
res.add(s);
if (left > 0)
generateParenthesisRe(res, left - 1, right, s + "(");
if (right > left)
generateParenthesisRe(res, left, right - 1, s + ")");
}
}