diff --git a/algorithms/backtrack/generate_parenthesis.py b/algorithms/backtrack/generate_parenthesis.py index 9b9eb8cf1..073cec96a 100644 --- a/algorithms/backtrack/generate_parenthesis.py +++ b/algorithms/backtrack/generate_parenthesis.py @@ -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 diff --git a/tests/test_backtrack.py b/tests/test_backtrack.py index dd290f759..c53f9f1e1 100644 --- a/tests/test_backtrack.py +++ b/tests/test_backtrack.py @@ -11,6 +11,7 @@ ) import unittest +from algorithms.backtrack.generate_parenthesis import * class TestAddOperator(unittest.TestCase): @@ -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() +