Created
July 25, 2017 11:52
-
-
Save 0001vrn/b7a234cba6f01b61e5781d7cb7885a54 to your computer and use it in GitHub Desktop.
Print all combinations of balanced parentheses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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