Skip to content

Commit

Permalink
generate_parenthesis (keon#384)
Browse files Browse the repository at this point in the history
* generate_parenthesis

* format
  • Loading branch information
RenliangShi authored and Hai Hoang Dang committed Aug 6, 2018
1 parent 48072b4 commit 3879607
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
20 changes: 17 additions & 3 deletions algorithms/backtrack/generate_parenthesis.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,30 @@
"""


def generate_parenthesis(n):
def generate_parenthesis_v1(n):
def add_pair(res, s, left, right):
if left == 0 and right == 0:
res.append(s)
return
if right > 0:
add_pair(res, s+")", left, right-1)
add_pair(res, s + ")", left, right - 1)
if left > 0:
add_pair(res, s+"(", left-1, right+1)
add_pair(res, s + "(", left - 1, right + 1)

res = []
add_pair(res, "", n, 0)
return res


def generate_parenthesis_v2(n):
def add_pair(res, s, left, right):
if left == 0 and right == 0:
res.append(s)
if left > 0:
add_pair(res, s + "(", left - 1, right)
if right > 0 and left < right:
add_pair(res, s + ")", left, right - 1)

res = []
add_pair(res, "", n, n)
return res
14 changes: 14 additions & 0 deletions tests/test_backtrack.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
)

import unittest
from algorithms.backtrack.generate_parenthesis import *


class TestAddOperator(unittest.TestCase):
Expand Down Expand Up @@ -170,3 +171,16 @@ def test_pattern_match(self):
self.assertTrue(pattern_match(pattern1, string1))
self.assertTrue(pattern_match(pattern2, string2))
self.assertFalse(pattern_match(pattern3, string3))

class TestGenerateParenthesis(unittest.TestCase):

def test_generate_parenthesis(self):
self.assertEqual(generate_parenthesis_v1(2), ['()()', '(())'])
self.assertEqual(generate_parenthesis_v1(3), ['()()()', '()(())', '(())()', '(()())', '((()))'])
self.assertEqual(generate_parenthesis_v2(2), ['(())', '()()'])
self.assertEqual(generate_parenthesis_v2(3), ['((()))', '(()())', '(())()', '()(())', '()()()'])

if __name__ == '__main__':

unittest.main()

0 comments on commit 3879607

Please sign in to comment.