-
Notifications
You must be signed in to change notification settings - Fork 617
/
valid_parantheses.java
95 lines (80 loc) · 3.11 KB
/
valid_parantheses.java
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
Generate all valid parentheses
Problem Statement: Write a program to generate all possible "n" pairs of balanced parantheses where "n" is the input from user.
For e.g if n = 2, the possible combinations are {}{}, {{}} only. I have solved it by storing the combination of parantheses
and calling for the next set recursively.
*/
import java.util.*;
import java.lang.*;
import java.io.*;
class valid_parantheses{
//function to print all valid pairs of parantheses by storing the count of opening and closing brackets
static void generate_parantheses(char str[], int pos, int n, int start, int end){
if(end == n){
for(int i = 0; i < str.length; i++){
//printing all pairs of parantheses
System.out.print(str[i]);
}
System.out.println();
return;
}
else{
//checking the condition for inserting the closing parantheses
if(start > end){
str[pos] = '}';
generate_parantheses(str, pos+1, n, start, end+1);
}
//checking the condition for inserting the opening parantheses
if(start < n){
str[pos] = '{';
generate_parantheses(str, pos+1, n, start+1, end);
}
}
}
//function to call the generate_parantheses function with initial values
static void valid_parantheses_call(char ans[], int n){
if( n > 0)
generate_parantheses(ans, 0, n, 0 , 0);
return;
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int n = 0;
n = sc.nextInt();
//generating a character array for storing parantheses
char [] arr = new char[2*n];
valid_parantheses_call(arr, n);
}
}
/*Test Cases:
1.
Input:
3
Output:
{}{}{}
{}{{}}
{{}}{}
{{}{}}
{{{}}}
2.
Input:
4
Output:
{}{}{}{}
{}{}{{}}
{}{{}}{}
{}{{}{}}
{}{{{}}}
{{}}{}{}
{{}}{{}}
{{}{}}{}
{{}{}{}}
{{}{{}}}
{{{}}}{}
{{{}}{}}
{{{}{}}}
{{{{}}}}
Time Complexity: O(2^n), where n is the number for which, pairs of balanced parantheses are to generated
Space Complexity: O(n), since we have created character array of size 2*n where n is the number for which, pairs of balanced parantheses are to generated
*/