diff --git a/Backtracking/generateParentheses.js b/Backtracking/generateParentheses.js new file mode 100644 index 0000000000..8414c95b08 --- /dev/null +++ b/Backtracking/generateParentheses.js @@ -0,0 +1,31 @@ +/** + * Problem Statement: Given a number n pairs of parentheses, try to Generate all combinations of valid parentheses; + * @param {number} n - number of given parentheses + * @return {string[]} res - array that contains all valid parentheses + * @see https://leetcode.com/problems/generate-parentheses/ + */ + +const generateParentheses = (n) => { + const res = [] + + const solve = (chres, openParenthese, closedParenthese) => { + if (openParenthese === n && closedParenthese === n) { + res.push(chres) + return + } + + if (openParenthese <= n) { + solve(chres + '(', openParenthese + 1, closedParenthese) + } + + if (closedParenthese < openParenthese) { + solve(chres + ')', openParenthese, closedParenthese + 1) + } + } + + solve('', 0, 0) + + return res +} + +export { generateParentheses } diff --git a/Backtracking/tests/GenerateParentheses.test.js b/Backtracking/tests/GenerateParentheses.test.js new file mode 100644 index 0000000000..d7431a1a3c --- /dev/null +++ b/Backtracking/tests/GenerateParentheses.test.js @@ -0,0 +1,5 @@ +import { generateParentheses } from '../generateParentheses' + +test('generate all valid parentheses of input 3', () => { + expect(generateParentheses(3)).toStrictEqual(['((()))', '(()())', '(())()', '()(())', '()()()']) +})