LeetCode算法笔记–Day35
22. Generate Parentheses
题目:
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
example
input: n = 3
output: [“((()))”,”(()())”,”(())()”,”()(())”,”()()()”]
My Answer:
方法一:递归

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| /** * @param {number} n * @return {string[]} */ var generateParenthesis = function(n) { let _res = []; let _str = ''; let dfs = function(_str,left,right){ if(left == 0 && right == 0){ _res.push(_str) return _res; } if(left > right){ return } if(left>0){ dfs(_str+'(',left-1,right) } if(right>0){ dfs(_str+')',left,right-1) } }
dfs(_str,n,n); return _res; };
|
