题目
题目链接:https://leetcode-cn.com/problems/generate-parentheses
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例:
输入:n = 3
输出:[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
解题记录
看一下规律,起始一定是'('
,左括号和右括号的个数一定相等且等于n,这里使用递归求出可行字符串插入到列表中:
class Solution {
int N;
List<String> total = new ArrayList<>();
public List<String> generateParenthesis(int n) {
N=n;
addStr("(", 1, 0);
return total;
}
public void addStr (String seq, int left, int right){
if (seq.length() == N*2){
total.add(seq);
}else{
if(left<N) addStr(seq+"(", left+1, right);
if(right<N && right < left) addStr(seq+")", left, right+1);
}
}
}
优化
String
类型换成char[]
class Solution {
int N;
List<String> result = new ArrayList<>();
public List<String> generateParenthesis(int n) {
N = n<<1;
char[] seq = new char[N];
addStr(seq, 0, N);
return result;
}
public void addStr(char[] seq, int count, int rest){
if (rest==0&&count==0){
result.add(new String(seq));
} else if (count>0&&rest>0){
seq[N-rest] = '(';
addStr(seq, count+1, rest-1);
seq[N-rest] = ')';
addStr(seq, count-1, rest-1);
} else if(rest>0){
seq[N-rest] = '(';
addStr(seq, count+1, rest-1);
}
}
}
速度略有提升
来源:oschina
链接:https://my.oschina.net/u/4412708/blog/3227490