左:左括弧をすべて使い切っていない限り、いつでも左括弧を挿入できます。右:構文エラーが発生しない限り、右のパレンを挿入できます。構文エラーはいつ発生しますか
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); //
}
}
結果は次のようになります。
(())
()()
しかし、私が得るものは次のとおりです。
(())
()()
())(
)(()
)()(
))((