Write a function to generate all possible n pairs of balanced parentheses.
For example, if n=1
{}
for n=2
{}{}
{{}}
Solution : Beautiful use of tail recursion.
public class Parentheses {
public static void main(String[] args) {
generate("",0,0,3);
}
public static void generate(String s, int open, int close, int n){
if(open==n && close==n){
System.out.println(""+s);
return;
}
if(close>open)
return;
if(open>=close && open<n){
generate(s+"{",open+1,close, n );
}
if(close < open){
generate(s+"}", open, close+1,n);
}
}
}
0 comments:
Post a Comment