Skip to content

Adding to backtracking #1289

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Feb 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions Backtracking/generateParentheses.js
Original file line number Diff line number Diff line change
@@ -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 }
5 changes: 5 additions & 0 deletions Backtracking/tests/GenerateParentheses.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { generateParentheses } from '../generateParentheses'

test('generate all valid parentheses of input 3', () => {
expect(generateParentheses(3)).toStrictEqual(['((()))', '(()())', '(())()', '()(())', '()()()'])
})