Skip to content

Instantly share code, notes, and snippets.

@0001vrn
Created July 25, 2017 11:52
Show Gist options
  • Select an option

  • Save 0001vrn/b7a234cba6f01b61e5781d7cb7885a54 to your computer and use it in GitHub Desktop.

Select an option

Save 0001vrn/b7a234cba6f01b61e5781d7cb7885a54 to your computer and use it in GitHub Desktop.
Print all combinations of balanced parentheses
#include <iostream>
using namespace std;
#define MAX_SIZE 100
void printParentheses(int n);
void _printParentheses(int pos, int n, int open, int close);
void printParentheses(int n)
{
if(n>0)
_printParentheses(0,n,0,0);
return;
}
void _printParentheses(int pos,int n,int open,int close)
{
static char str[MAX_SIZE];
if(close == n)
{
printf("%s\n",str);
return;
}
else
{
if(open>close)
{
str[pos]='}';
_printParentheses(pos+1,n,open,close+1);
}
if(open<n)
{
str[pos]='{';
_printParentheses(pos+1,n,open+1,close);
}
}
}
int main() {
// your code goes here
int n = 5;
printParentheses(n);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment