题目
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
有效括号组合需满足:左括号必须以正确的顺序闭合。
示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1
输出:["()"]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法一
class Solution {
public List<String> generateParenthesis(int n) {
//暴力解法,先枚举出所有的情况,然后去掉不符合的情况
List<String> result = new ArrayList<>();
backTrace(0, result, n, new StringBuilder());
return result;
}
public void backTrace(int index, List<String> list, int n, StringBuilder sb){
if(index == 2 * n){
if(valid(sb.toString()))
list.add(sb.toString());
return;
}
sb.append('(');
backTrace(index + 1, list, n, sb);
sb.deleteCharAt(index);
sb.append(')');
backTrace(index + 1, list, n, sb);
sb.deleteCharAt(index);
}
public boolean valid(String str){
int balance = 0;
for(int i = 0; i < str.length(); i ++){
if(str.charAt(i) == '(')
balance ++;
else
balance --;
if(balance < 0)
return false;
}
return balance == 0;
}
}
解法二
class Solution {
public List<String> generateParenthesis(int n) {
//回溯解法改进方案,一边判断一边添加
List<String> result = new ArrayList<>();
backtrace(n, 0, 0, result, new char[2 * n]);
return result;
}
private void backtrace(int n, int open, int close, List<String> result, char[] t){
if(close == n && open == n){
result.add(new String(t));
return;
}
if(open < n){
t[open + close] = '(';
backtrace(n, open + 1, close, result, t);
}
if(close < open){
t[open + close] = ')';
backtrace(n, open, close + 1, result, t);
}
}
}