思路:最终符合要求的字符串中,左括号和右括号个数都是n,而且在字符串生成过程中,左括号的剩余个数一定小于等于右括号剩余个数,如果左右括号剩余个数都为0,说明找到一个符合题意的字符串了,保存下来。所以可以采用递归,分别添加左括号和右括号,根据以上条件设置递归出口。
代码:
public class GenerateParentheses22 {
public static void main(String[] args) {
System.out.println(new GenerateParentheses22().generateParenthesis(3));
}
public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<>();
int left = n;
int right = n;
helpGenerateParenthesis(left, right, "", list);
return list;
}
public void helpGenerateParenthesis(int left, int right, String s, List<String> list) {
if (left == 0 && right == 0) {
list.add(new String(s));
}
if (left < 0 || right < 0 || left > right)
return;
helpGenerateParenthesis(left - 1, right, s + "(", list);
helpGenerateParenthesis(left, right - 1, s + ")", list);
}
}
输出: