Skip to content

Commit ed54549

Browse files
committed
Create valid_parenthesis_permutations.py
1 parent 1c2009f commit ed54549

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

valid_parenthesis_permutations.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Given a num, get all the valid parenthesis permutations.
2+
# Observations:
3+
# - All permutations start with opens
4+
# - Base case: if num of open used == num of closed used
5+
# - Num of opens used up, then next to the end must be closed
6+
7+
import unittest
8+
9+
10+
def valid_parens_perms(num):
11+
12+
result = []
13+
14+
def recurse(substr, left, right):
15+
if left == 0 and right == 0:
16+
result.append(substr)
17+
return
18+
19+
elif left == 0:
20+
recurse(substr + ')', left, right - 1)
21+
22+
elif left < right:
23+
recurse(substr + '(', left - 1, right)
24+
recurse(substr + ')', left, right - 1)
25+
26+
elif left == right:
27+
recurse(substr + '(', left - 1, right)
28+
29+
recurse('', num, num)
30+
31+
return result
32+
33+
34+
class Testing(unittest.TestCase):
35+
def test_valid_parens_perms(self):
36+
self.assertEqual(valid_parens_perms(1), ['()'])
37+
self.assertEqual(valid_parens_perms(2), ['(())', '()()'])
38+
self.assertEqual(valid_parens_perms(3), ['((()))', '(()())', '(())()', '()(())', '()()()'])
39+
self.assertEqual(valid_parens_perms(4), ['(((())))', '((()()))', '((())())', '((()))()', '(()(()))', '(()()())', '(()())()', '(())(())', '(())()()', '()((()))', '()(()())', '()(())()', '()()(())', '()()()()'])
40+
41+
42+
if __name__ == '__main__':
43+
unittest.main()

0 commit comments

Comments
 (0)