• RSS
  • Facebook
  • Twitter

Knowledge is Power.

  • Who you are ?

    Working on machines without understanding them ? Then you should be here..

  • Where you are ?

    Geographical location should not become a barrier to Share our knowledge.

  • What do you do ?

    Puzzles and Interview question are intended to be discussed here.

    Thursday, February 25, 2010

    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