数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1
输出:["()"]
回溯法
class Solution {
public List<String> generateParenthesis(int n) {
List<String> results = new ArrayList<>();
if (n == 0)
return results;
backtrack(results, new StringBuilder(), 0, 0, n);
return results;
}
private void backtrack(List<String> results, StringBuilder s, int open, int close, int n) {
if (s.length() == n * 2) {
results.add(s.toString());
} else {
if (open < n) {
s.append('(');
backtrack(results, s, open + 1, close, n);
s.deleteCharAt(s.length() - 1);
}
if (close < open) {
s.append(')');
backtrack(results, s, open, close + 1, n);
s.deleteCharAt(s.length() - 1);
}
}
}
}
深度优先遍历
深度优先遍历与回溯法原理其实一样
class Solution {
public List<String> generateParenthesis(int n) {
List<String> results = new ArrayList<>();
if (n == 0)
return results;
dfs("", n, n, results);
return results;
}
private void dfs(String curStr, int open, int close, List<String> results) {
if (open == 0 && close == 0) {
results.add(curStr);
} else {
if (open > close)
return;
if (open > 0) {
dfs(curStr + "(", open - 1, close, results);
}
if (close > 0) {
dfs(curStr + ")", open, close - 1, results);
}
}
}
}
广度优先遍历
依次遍历每一种长度的可能的 有效的括号组合
class Solution {
class Node {
private String st;
private int left;
private int right;
public Node(String st, int left, int right) {
this.st = st;
this.left = left;
this.right = right;
}
}
public List<String> generateParenthesis(int n) {
List<String> results = new ArrayList<>();
if (n == 0)
return results;
Queue<Node> queue = new LinkedList<>();
queue.offer(new Node("", n, n));
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
Node curNode = queue.poll();
if (curNode.left == 0 && curNode.right == 0) {
results.add(curNode.st);
}
if (curNode.left > 0) {
queue.offer(new Node(curNode.st + "(", curNode.left - 1, curNode.right));
}
if (curNode.right > 0 && curNode.left < curNode.right) {
queue.offer(new Node(curNode.st + ")", curNode.left, curNode.right - 1));
}
}
}
return results;
}
}