您的位置:首页 > 其它

LeetCode 22 Generate Parentheses (DFS 构造)

2017-07-08 13:22 411 查看
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

题目分析:只要保证左括号个数大于等于右括号且小于等于n即可,DFS构造
public class Solution {

public void DFS(int l, int r, int n, String str, List<String> ans) {
if (l == n && r == n) {
ans.add(str);
return;
}
if (l > r) {
DFS(l, r + 1, n, str + ")", ans);
}
if (l < n) {
DFS(l + 1, r, n, str + "(", ans);
}
}

public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList<>();
DFS(0, 0, n, "", ans);
return ans;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: