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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
题目分析及实现
最基础的一种方法就是使用递归法,全排列所有可能出现的情况,然后对每一种进行判断,合格的加入队列。
判断是否合格的方式,设定temp值==0,遇见左括号+1,右括号减一。若是中间出现temp小于0的情况,就是不合格。最后出现temp不等于0的话也是不合格。
class Solution {
public List<String> generateParenthesis(int n) {
List<String> combinations = new ArrayList();
char current [] = new char[2*n];
generateALL(current,0,combinations);
return combinations;
}
public void generateALL(char []current,int pos,List<String> list){
if(pos == current.length){
if(valid(current))
list.add(new String (current));
}else{
current[pos] = '(';
generateALL(current,pos+1,list);
current[pos] = ')';
generateALL(current,pos+1,list);
}
}
public boolean valid(char []a){
int temp = 0;//个数
for(char x : a){
if(temp < 0)
return false;
if(x == '(')
temp++;
else
temp--;
}
return (temp == 0);
}
}
然后下面说的提高性能的方法,emmmmm,没有看懂。。。。就这个就简单的凑活用吧我就。