Skip to content

Commit 8af2fdd

Browse files
committed
1 parent 937ce83 commit 8af2fdd

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

backtracking/generate_parenthesis.py

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
"""
2+
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
3+
Constraints: 1 <= n <= 8
4+
Problem source: https://leetcode.com/problems/generate-parentheses/
5+
"""
6+
7+
class Solution:
8+
def generateParenthesis(self, n):
9+
valid = []
10+
11+
# Helper function to generate valid combinations
12+
def generate(s, open_count, close_count):
13+
if open_count == 0 and close_count == 0:
14+
valid.append(s)
15+
return
16+
17+
if open_count > 0:
18+
s += '('
19+
generate(s, open_count - 1, close_count)
20+
s = s[:-1]
21+
22+
if close_count > 0 and open_count < close_count:
23+
s += ')'
24+
generate(s, open_count, close_count - 1)
25+
s = s[:-1]
26+
27+
if n < 0:
28+
raise ValueError("Input value must be non-negative")
29+
30+
# Start the generation process with an empty string and n opening and closing parentheses
31+
generate('', n, n)
32+
"""
33+
The function employs backtracking to generate all valid combinations of n pairs of parentheses. It maintains two counters, open_count and close_count, representing available open and close parentheses.
34+
35+
It starts with an empty string s and both counters set to n.
36+
37+
It recursively explores two possibilities:
38+
39+
Adding an open parenthesis '(' if open_count > 0.
40+
Adding a close parenthesis ')' if close_count > 0 and there are open parentheses available (i.e., open_count < close_count).
41+
When both counters reach zero, it means a valid combination is formed, and it's added to the valid list.
42+
43+
The code then tries different combinations by backtracking (removing the last added parenthesis) and continues until all possibilities are exhausted.
44+
45+
The input is validated to ensure it's a non-negative integer, and a ValueError is raised for invalid input.
46+
47+
The valid combinations are returned as the result.
48+
"""
49+
50+
return valid
51+
52+
53+
try:
54+
# Input the value of n from the user
55+
n = int(input("Enter a value for n: "))
56+
57+
# Create an instance of the Solution class and generate valid combinations
58+
solution = Solution()
59+
result = solution.generateParenthesis(n)
60+
61+
# Return the valid combinations
62+
print(result)
63+
except ValueError:
64+
print("Invalid input. Please enter a non-negative integer.")

0 commit comments

Comments
 (0)