forked from chitwang/iitk-sem1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
balanced-parantheses.c
76 lines (62 loc) · 1.21 KB
/
balanced-parantheses.c
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
70
71
72
73
74
75
76
/*You are given a number N. And, your task is print all string of length 2*N which consist of N opening and N closing parentheses in lexico-graphical order.
Input Format
A single line containing an integer N.
Output Format
Print all strings of length 2*N which consist of N opening and N closing parentheses in lexico-graphical order.
Example Input
3
Example Output
((()))
(()())
(())()
()(())
()()()*/
// solution:
#include <stdio.h>
void func(int n, char arr[], int up, int down)
{
int x = up + down;
if (down == n)
{
for (int i = 0; i < x; i++)
{
printf("%c", arr[i]);
}
printf("\n");
return;
}
if (up > down && up < n)
{
arr[x] = '(';
func(n, arr, up + 1, down);
arr[x] = ')';
func(n, arr, up, down + 1);
return;
}
if (up > down && up == n)
{
arr[x] = ')';
func(n, arr, up, down + 1);
}
if (up > n)
{
return;
}
if (up == down)
{
arr[x] = '(';
func(n, arr, up + 1, down);
return;
}
if (down > up)
{
return;
}
}
int main()
{
int n;
scanf("%d", &n);
char arr[2 * n];
func(n, arr, 0, 0);
}