力扣 22. 括號生成

予真發表於2024-03-10

數字 n 代表生成括號的對數,請你設計一個函式,用於能夠生成所有可能的並且 有效的 括號組合。

示例 1:

輸入:n = 3
輸出:["((()))","(()())","(())()","()(())","()()()"]

示例 2:

輸入:n = 1
輸出:["()"]

class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
StringBuilder path = new StringBuilder();
backtrack(res, path, 0, 0, n);
return res;
}

private void backtrack(List<String> res, StringBuilder path, int open, int close, int max) {
if (path.length() == max * 2) {
res.add(path.toString());
return;
}
if (open < max) {
backtrack(res, path.append("("), open + 1, close, max);
path.deleteCharAt(path.length()-1);
}
if (close < open) {
backtrack(res, path.append(")"), open, close + 1, max);
path.deleteCharAt(path.length()-1);
}
}
}

相關文章