题目内容
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example:
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
分析过程
- 题目归类:
递归删除题目
- 题目分析:
每次加入一个值,之后需要删除掉
- 边界分析:
- 方法分析:
- 测试用例构建
代码实现
class Solution {
List<String> list = new ArrayList<>();
StringBuilder sb = new StringBuilder();
public List<String> generateParenthesis(int n) {
if(n<=0)
return list;
if (n==1){
list.add("()");
return list;
}
return parenthesis(n,0);
}
public List<String> parenthesis(int n,int flag){
if(n==0&&flag==0){
list.add(new String(sb+""));
return list;
}
if(n!=0){
sb.append("(");
parenthesis(n-1,flag+1);
sb.delete(sb.length()-1,sb.length());
}
if(flag!=0){
sb.append(")");
parenthesis(n,flag-1);
sb.delete(sb.length()-1,sb.length());
}
return list;
}
}
效率提高
拓展问题