import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int整型
* @return string字符串ArrayList
*/
public ArrayList<String> generateParenthesis (int n) {
// write code here
ArrayList<String> ret = new ArrayList<String>();
produce(ret, n, "");
return ret;
}
public void produce(ArrayList<String> ret, int n, String str) {
if (str.length() > 2*n) {
return;
}
if (str.length() == 2*n){
if (isLegal(str)) {
ret.add(str);
}
return;
}
produce(ret, n, str+"(");
produce(ret, n, str+")");
}
public Boolean isLegal(String str) {
int fast = 0;
int i = 0;
while (i < str.length()) {
if (str.charAt(i) == ')'){
fast--;
}else {
fast++;
}
if (fast < 0){
return false;
}
i++;
}
if (fast != 0) {
return false;
}
return true;
}
}