[LeetCode] 22. Generate Parentheses ☆☆
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
解法:
采用递归的方法,对于给定数字n,最终组成的字符串肯定是左括号和右括号各n个。用left和right分别表示剩余左右括号的个数,如果在某次递归时,左括号的个数大于右括号的个数,说明此时生成的字符串中右括号的个数大于左括号的个数,即会出现')('这样的非法串,所以这种情况直接返回,不继续处理。如果left和right都为0,则说明此时生成的字符串已有3个左括号和3个右括号,且字符串合法,则存入结果中后返回。如果以上两种情况都不满足,若此时left大于0,则调用递归函数,注意参数的更新,若right大于0,则调用递归函数,同样要更新参数。代码如下:
public class Solution { public List<String> generateParenthesis(int n) { List<String> res = new ArrayList<>(); if (n < 1) return res; helper(res, "", n, n); return res; } public void helper(List<String> list, String str, int left, int right) { if (left == 0 && right == 0) { list.add(str); return; } if (left > 0) { helper(list, str + "(", left - 1, right); } if (right > 0 && left < right) { // 添加')'还必须满足剩余的'('比')'少 helper(list, str + ")", left, right - 1); } } }