22. Generate Parentheses——回溯法初探
阿新 • • 發佈:2019-02-04
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
完全想不到,在看了別人的演算法後,自己畫圖加以理解才明白,主要是利用兩個條件去限制迭代,把不合格的排除掉,第一個open < max
的條件篩選掉的用感嘆號表示,第二個條件close < open
程式碼如下:
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
StringBuilder sb = new StringBuilder();
helper(res, sb, 0 , 0, n);
return res;
}
public void helper(List<String> res, StringBuilder sb, int open, int close, int max){
if(open == max && close == max){
res.add(sb.toString());
return;
}
if(open < max){
sb.append("(");
helper(res, sb, open +1, close, max);
sb.setLength(sb.length()-1);
}
if(close < open){
sb.append(")");
helper(res, sb, open, close+1, max);
sb.setLength(sb.length()-1);
}
}
}