Adding to backtracking (#1289)

* adding generate-parenthses algorithm

* adding generateParenthses algorithm

* adding generate parentheses algorithm

* fixing comments according to the JDoc comments, cleaning code

* fixing comments
This commit is contained in:
Ramzi-Abidi
2023-02-13 12:39:31 +01:00
committed by GitHub
parent c40e4cf4d4
commit 49bd1fd0c2
2 changed files with 36 additions and 0 deletions

View File

@ -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 }

View File

@ -0,0 +1,5 @@
import { generateParentheses } from '../generateParentheses'
test('generate all valid parentheses of input 3', () => {
expect(generateParentheses(3)).toStrictEqual(['((()))', '(()())', '(())()', '()(())', '()()()'])
})