Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
DFS
Time Complexity
O(2^n)
It is traverse of a tree.
The level is 2n.
O(2^2n - 1) --> O(2^n)
Space Complexity
O(N)
思路
We can think it as a tree. The depth of the tree is the length of the parentheses. The base case if left + right = 2*n. The recursion rule is add "(" or ")". A valid parentheses should following left parentheses should less than n and the right parentheses should less or equal to left parentheses.
代码
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>();
if(n == 0) return res;
StringBuilder sb = new StringBuilder();
dfs(res, sb, n, 0, 0);
return res;
}
private void dfs(List<String> res, StringBuilder sb, int n, int left, int right){
if(left == n && right == n) res.add(sb.toString()); return;
//add left
if(left < n){
sb.append("(");
dfs(res, sb, n, left + 1, right);
sb.deleteCharAt(sb.length() - 1);
}
//add right
if(right < left){
sb.append(")");
dfs(res, sb, n, left, right + 1);
sb.deleteCharAt(sb.length() - 1);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。