From 41029ba380080d1e73135bf497a8c4002ed65c1f Mon Sep 17 00:00:00 2001 From: Anshul shrivas <128448038+anshul-132002@users.noreply.github.com> Date: Sun, 8 Oct 2023 10:03:56 +0530 Subject: [PATCH 1/2] Added parentheses using backtracking --- backtracking/parentheses.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 backtracking/parentheses.py diff --git a/backtracking/parentheses.py b/backtracking/parentheses.py new file mode 100644 index 000000000000..f63298ce7caa --- /dev/null +++ b/backtracking/parentheses.py @@ -0,0 +1,18 @@ +def generateParenthesis(n): + def backtrack(combination, open_count, close_count): + if len(combination) == 2 * n: + valid_combinations.append(combination) + return + if open_count < n: + backtrack(combination + '(', open_count + 1, close_count) + if close_count < open_count: + backtrack(combination + ')', open_count, close_count + 1) + + valid_combinations = [] + backtrack('', 0, 0) + return valid_combinations + +n = 3 # You can change the value of n to generate combinations for a different number of pairs of parentheses +result = generateParenthesis(n) +for combination in result: + print(combination) From 96970d6443ce67b946259038c28888e0583bd25f Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sun, 8 Oct 2023 04:38:41 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- backtracking/parentheses.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/backtracking/parentheses.py b/backtracking/parentheses.py index f63298ce7caa..ea70f638c1ee 100644 --- a/backtracking/parentheses.py +++ b/backtracking/parentheses.py @@ -4,14 +4,15 @@ def backtrack(combination, open_count, close_count): valid_combinations.append(combination) return if open_count < n: - backtrack(combination + '(', open_count + 1, close_count) + backtrack(combination + "(", open_count + 1, close_count) if close_count < open_count: - backtrack(combination + ')', open_count, close_count + 1) + backtrack(combination + ")", open_count, close_count + 1) valid_combinations = [] - backtrack('', 0, 0) + backtrack("", 0, 0) return valid_combinations + n = 3 # You can change the value of n to generate combinations for a different number of pairs of parentheses result = generateParenthesis(n) for combination in result: