0

So here's the problem. For a given n we need to generate all valid parenthesis.

For e.g, for n=2 the possible output will be ()(), (()))

So I tried solving using recursion and backtracking.

I take two variables, open_bracket and close_bracket along with a ds to store the parenthesis.

Here's my recursive diagram looks like

Here's my recursive diagram looks like

So with that I tried this:

function generatePArenthesis(n, open_bracket=0, close_bracket=0, ds=[]){
    if(open_bracket === n && close_bracket === n){
    console.log(ds.toString());
    return
  }
  
  if(open_bracket < n){
    ds.push('(');
    generatePArenthesis(n, open_bracket+ 1, close_bracket, ds);
  }
  
  if(close_bracket<open_bracket){
    ds.push(')');
    generatePArenthesis(n, open_bracket, close_bracket +1, ds);
  }
  
}

generatePArenthesis(2)

when I dry run this program for n=2 it does seem to produce the above recursive diagram. But doesn't give me the correct output. Where am I making mistake?

1 Answer 1

1

Restore ds after recursive calls:

function generatePArenthesis(n, open_bracket=0, close_bracket=0, ds=[]){
    if(open_bracket === n && close_bracket === n){
    console.log(ds.toString());
    return
  }
  
  if(open_bracket < n){
    ds.push('(');
    generatePArenthesis(n, open_bracket+ 1, close_bracket, ds);
    ds.pop();
  }
  
  if(close_bracket<open_bracket){
    ds.push(')');
    generatePArenthesis(n, open_bracket, close_bracket +1, ds);
        ds.pop();
  }
  
}

generatePArenthesis(3)

Sign up to request clarification or add additional context in comments.

4 Comments

can you please explain why as in my recursive tree, I'm pushing into the existing content without clearing it and it still produces the output correctly.
When you first made (,(,),) in left big branch, ds contains 4 items and it is used in the right branch, so you add ( not to (,) as you wanted but to (,(,),)
You are using single instance of ds everywhere. You can create new copies in recursive calls (I don't know JS enough, but something like generatePArenthesis(n, open_bracket+ 1, close_bracket, ds +'(')
That’s right. Like this […ds, ‘(‘]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.