Skip to content

Commit 9ebbe86

Browse files
Merge pull request #13 from codewithme-py/feat/generate-parentheses-0022
problem solution & test 0022 + chore: fix makefile
2 parents 2292fe3 + 2e44448 commit 9ebbe86

File tree

4 files changed

+51
-3
lines changed

4 files changed

+51
-3
lines changed

Makefile

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
.PHONY: problem
22
problem:
3-
@if [ -z '$(filter-out problem,$(MAKECMDGOALS))']; then \
3+
@if [ -z '$(filter-out problem,$(MAKECMDGOALS))' ]; then \
44
echo 'Usage: make problem <problem_number>'; \
55
exit 1; \
66
fi
77
@uv run scripts/create_problem.py $(filter-out problem,$(MAKECMDGOALS))
8-
8+
9+
%:
10+
@:
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution:
2+
def generateParenthesis(self, n: int) -> list[str]:
3+
"""
4+
Generate all valid combinations of n pairs of parentheses.
5+
6+
Uses backtracking: build combinations by adding '(' or ')'
7+
until the length reaches 2*n.
8+
9+
Validity rules:
10+
- '(' can be added if open_count < n
11+
- ')' can be added if close_count < open_count
12+
13+
Args:
14+
n: Number of pairs of parentheses (1 <= n <= 8)
15+
16+
Returns:
17+
List of all valid combinations of parentheses
18+
19+
Time Complexity: O(4^n / sqrt(n)) - Catalan number
20+
Space Complexity: O(n) - recursion depth
21+
"""
22+
open_bracket, close_bracket = '(', ')'
23+
result: list[str] = []
24+
def backtrack(current: str, open_count: int, close_count: int) -> None:
25+
if len(current) == n * 2:
26+
result.append(current)
27+
return
28+
if open_count < n:
29+
backtrack(current + open_bracket, open_count + 1, close_count)
30+
if close_count < open_count:
31+
backtrack(current + close_bracket, open_count, close_count + 1)
32+
backtrack('', 0, 0)
33+
return result
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import pytest
2+
3+
from solutions.generate_parentheses_0022 import Solution
4+
5+
6+
@pytest.mark.parametrize('n, expected', [
7+
(1, ['()']),
8+
(2, ['(())', '()()']),
9+
(3, ['((()))', '(()())', '(())()', '()(())', '()()()']),
10+
])
11+
def test_solution(n: int, expected: list[str]) -> None:
12+
sol = Solution()
13+
assert sol.generateParenthesis(n) == expected

uv.lock

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)