Skip to content

Commit 032dbab

Browse files
committed
Generate All Balanced Parentheses - Parentheses Problems
1 parent 821471f commit 032dbab

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package com.java.parentheses;
2+
3+
import java.util.Scanner;
4+
5+
/*
6+
* Generate Balanced Parentheses
7+
*
8+
* Given n pairs of parentheses
9+
* Write a java program to generate all combinations of
10+
* well-formed or balanced parentheses
11+
*
12+
* input 1
13+
* ()
14+
*
15+
* input 2
16+
* ()()
17+
* (())
18+
*
19+
*/
20+
public class GenerateBalancedParentheses {
21+
public static void main(String[] args) {
22+
Scanner scanner = new Scanner(System.in);
23+
int N = scanner.nextInt();
24+
generateParentheses(0, 0, "",N);
25+
scanner.close();
26+
}
27+
28+
public static void generateParentheses(int openCount,int closeCount,String parentheses,int N){
29+
if(closeCount == N){
30+
System.out.println(parentheses);
31+
return;
32+
}
33+
if(openCount < N)
34+
generateParentheses(openCount+1, closeCount, parentheses+"(",N);
35+
if(openCount > closeCount)
36+
generateParentheses(openCount, closeCount+1, parentheses+")",N);
37+
}
38+
}
39+
/*
40+
INPUT
41+
3
42+
43+
OUTPUT
44+
((()))
45+
(()())
46+
(())()
47+
()(())
48+
()()()
49+
50+
INPUT
51+
4
52+
53+
OUTPUT
54+
(((())))
55+
((()()))
56+
((())())
57+
((()))()
58+
(()(()))
59+
(()()())
60+
(()())()
61+
(())(())
62+
(())()()
63+
()((()))
64+
()(()())
65+
()(())()
66+
()()(())
67+
()()()()
68+
*/

0 commit comments

Comments
 (0)