leetcode22 括号生成
从本阶段开始按照专题刷lc。目前进行回溯(backTracking)的练习。
本题不难,基本是一个子集树的回溯思路,剪枝条件是能够构成有效括号组(用栈判定)和左右括号的数量都不会超过总数的一半。
代码:
class Solution {
List<String> res = null;
char[] x = null;
int N = 0;
int cntl = 0;
int cntr = 0;
// 检查到现在为止的结果是否可行
private boolean check(int pos){
Stack<Character> test = new Stack();
test.push(x[1]);
for(int i = 2;i <= pos;i++){
if(!test.isEmpty() && test.peek() == ')'){
return false;
}else{
if(x[i] == '(') test.push('(');
if(x[i] == ')') {
if(!test.isEmpty())
test.pop();
else{
return false;
}
}
}
}
if(pos == N && test.isEmpty() || test.isEmpty() || pos < N && test.peek()=='(')
return true;
return false;
}
void traceBack(int pos){
if(pos > N){
res.add(String.valueOf(x,1,N));
}else{
x[pos] = '(';
cntl++;
if(check(pos) && cntl <= N/2 && cntr <= N/2){
traceBack(pos+1);
}
cntl--;
x[pos] = ')';
cntr++;
if(check(pos) && cntl <= N/2 && cntr <= N/2){
traceBack(pos+1);
}
cntr--;
}
}
public List<String> generateParenthesis(int n) {
N = 2*n;
res = new ArrayList();
x = new char[500];
traceBack(1);
return res;
}
}
6ms 38.4MB