括号生成
给出n对括号,请编写一个函数来生成所有的由n对括号组成的合法组合。
例如,给出n=3,解集为:
“((()))”, “(()())”, “(())()”, “()()()”, “()(())”
一、思路
- 采用递归的思想。
- 比较左括号及右括号数量。
- 若左右括号均已使用完毕,则将该字符串加入最终结果中。
- 若剩余左括号数与右括号数相等,则下一个必须添加左括号。(不存在剩余左括号多于有括号的情况)
- 若剩余左括号数小于右括号数,则下一个添加的可以为左括号,也可以为右括号。
二、代码
import java.util.*;
public class Solution {
ArrayList<String> res = new ArrayList<>();
public ArrayList<String> generateParenthesis (int n) {
// write code here
if(n <= 0){
return res;
}
getParenthesis("",n,n);
return res;
}
private void getParenthesis(String str, int left, int right){
if(left == 0 && right == 0){
res.add(str);
return;
}
if(left == right){
// 剩余左括号和右括号数目相等,下一个只能使用左括号
getParenthesis(str + "(",left-1,right);
}
else if(left < right){
// 剩余左括号小于右括号,下一个可以使用左括号也可以使用右括号
if(left > 0){
getParenthesis(str + "(", left -1,right);
}
getParenthesis(str + ")",left,right - 1);
}
}
}