forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate_valid_parenthesis.cpp
70 lines (60 loc) · 1.36 KB
/
generate_valid_parenthesis.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*Problem Statement:
You are given a number n, your job is to find all the n balanced parenthesis
combinations possible */
#include <bits/stdc++.h>
using namespace std;
/*Function description :
At any index i,
BASE CASE :
The combination of brackets can at maximum reach 2*n length
therefore, if index reaches 2*n then print combination
RECURSIVE CASE:
1) If an open bracket is to be generated in the combination then,
count of(open) bracket should be less than n
2) If a closed bracket is to be generated in the combination then,
count of(close) bracket should be less than count of(open) bracket */
void FindValidParenthesis(char *out, int n, int index, int open, int close)
{
if (index == 2 *n)
{
out[index] = '\0';
cout << out << endl;
return;
}
//If the number of open brackets is less than n
if (open < n)
{
out[index] = '(';
FindValidParenthesis(out, n, index + 1, open + 1, close);
}
//If the number of close brackets is less than the number of open brackets
if (close < open)
{
out[index] = ')';
FindValidParenthesis(out, n, index + 1, open, close + 1);
}
return;
}
int main()
{
int n;
cin >> n;
char out[1000];
int index = 0;
FindValidParenthesis(out, n, 0, 0, 0);
return 0;
}
/*Examples :
1)Input : n = 2
Output-
(())
()()
2)Input : n = 3
Output-
((()))
(()())
(())()
()(())
()()()
Time Complexity : O(2^n)
Space Complexity : O(n) */