Open larscheng opened 5 months ago
暴力递归
递归生成完整数量的括号字符数组,递归过程中校验每轮的括号数组是否有效
代码
class Solution1 {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
createAll(new char[2*n],0,res);
return res;
}
private void createAll(char[] chars, int index, List<String> res) {
if (index==chars.length){
if (valid(chars)){
res.add(new String(chars));
}
}else {
chars[index]='(';
createAll(chars,index+1,res);
chars[index]=')';
createAll(chars,index+1,res);
}
}
private boolean valid(char[] chars) {
int blacne = 0;
for (char c : chars) {
if (c=='('){
++blacne;
}else {
--blacne;
}
if (blacne<0){
return false;
}
}
return blacne==0;
}
}
回溯
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
backtrack(res, new StringBuilder(), 0, 0, n);
return res;
}
private void backtrack(List<String> res, StringBuilder cur, int left, int right, int max) {
if(cur.length()==max*2){
res.add(cur.toString());
return;
}
if (left < max) {
cur.append('(');
backtrack(res, cur, left + 1, right, max);
cur.deleteCharAt(cur.length() - 1);
}
if (right < left) {
cur.append(')');
backtrack(res, cur, left, right + 1, max);
cur.deleteCharAt(cur.length() - 1);
}
}
}
22. 括号生成