leetcode solution

https://leetcode.com/problems/generate-parentheses/

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:

"((()))", "(()())", "(())()", "()(())", "()()()"

This is an easy problem. The keyword is all combinations.

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

public class {

* @param n n pairs
* @return All combinations of well-formed parentheses
*/

public ArrayList<String> generateParenthesis(int n) {
// Write your code here
ArrayList<String> result = new ArrayList<String>();
String temp = new String();

helper(result, temp, n, 0, 0);

return result;
}
private void helper(ArrayList<String> result, String temp, int n,
int leftParentheses, int rightParentheses)
{

if (temp.length() == 2 * n) {
result.add(temp);
}

if (leftParentheses < n) {
helper(result, temp + '(', n, leftParentheses + 1, rightParentheses);
}
if (rightParentheses < leftParentheses) {
helper(result, temp + ')', n, leftParentheses, rightParentheses + 1);
}

return;
}
}