Left:只要我们没有用完所有的左括号,我们总是可以插入一个左括号。右:只要不会导致语法错误,我们可以插入右括号。我们什么时候会收到语法错误
public class parentheses {
public static void printPar(int l, int r, char[] str, int count){ //Use recursion method to
// print the parentheses
if(l == 0 && r == 0){ //if there are no parentheses available, print them out
System.out.println(str); //Print out the parentheses
}
else{
if(l > 0){ // try a left paren, if there are some available
str[count] = '(';
printPar(l - 1, r, str, count + 1); //Recursion
}
if(r > 0){ // try a right paren, if there are some available
str[count] = ')';
printPar(l, r - 1, str, count + 1); //Recursion
}
}
}
public static void printPar(int count){
char[] str = new char[count*2]; // Create a char array to store the parentheses
printPar(count,count,str,0); //call the printPar method, the parameters are the left,
//the right parentheses, the array to store the
//parenthese, and the counter
}
public static void main(String[] args) {
// TODO Auto-generated method stub
printPar(2); //
}
}
结果应该是:
(())
()()
但我得到的是:
(())
()()
())(
)(()
)()(
))((