Given n
pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1 Output: ["()"]
Constraints:
1 <= n <= 8
括号生成。
题意是给一个数字N,请返回由N对括号组成的所有可能的括号对。这是典型的backtracking回溯类的题目,基础题,一定要会。思路是创建一个helper函数表示当前拼接的情况cur,剩下的left括号数量和剩下的right括号数量。
- 任何时候,如果left剩下的比right多(说明递归过程中多加了right),一定不对,则跳出递归
- 如果left和right都用完则跳出递归函数并加入当前结果到结果集
- 如果left还有,则left--继续递归
- 如果right还有,则right--继续递归
时间O(4的N次方除以根号N) - 这是卡特兰数的性质
空间O(4的N次方除以根号N)
Java实现
1 class Solution { 2 public List<String> generateParenthesis(int n) { 3 List<String> res = new ArrayList<>(); 4 helper(res, "", n, n); 5 return res; 6 } 7 8 private void helper(List<String> res, String cur, int left, int right) { 9 if (left > right) { 10 return; 11 } 12 if (left == 0 && right == 0) { 13 res.add(cur); 14 return; 15 } 16 if (left > 0) { 17 helper(res, cur + "(", left - 1, right); 18 } 19 if (right > 0) { 20 helper(res, cur + ")", left, right - 1); 21 } 22 } 23 }
JavaScript实现
1 /** 2 * @param {number} n 3 * @return {string[]} 4 */ 5 var generateParenthesis = function(n) { 6 let res = []; 7 var helper = function(left, right, cur) { 8 // corner case 9 if (left > right) { 10 return; 11 } 12 13 // normal case 14 if (left == 0 && right == 0) { 15 res.push(cur); 16 return; 17 } 18 if (left > 0) { 19 helper(left - 1, right, cur + '('); 20 } 21 if (right > 0) { 22 helper(left, right - 1, cur + ')'); 23 } 24 }; 25 helper(n, n, ''); 26 return res; 27 };