22. Generate Parentheses
2017-10-22 21:22
330 查看
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 parenthesis => n left + n right => 2*n positions.Each time, one left or right should be chosen.
We can always pick left.
If there are more right remained, we can put right.
of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n =
3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
做出来了 效率还行
n parenthesis => n left + n right => 2*n positions.Each time, one left or right should be chosen.
We can always pick left.
If there are more right remained, we can put right.
public ArrayList<String> generateParenthesis(int n) { ArrayList<String> results = new ArrayList<>(); generateParenthesis(results, "", n, n); return results; } public void generateParenthesis(ArrayList<String> results, String prefix, int left, int right) { if (left == 0 && right == 0) { results.add(prefix); return; } if (left > 0) { generateParenthesis(results, prefix+"(", left-1, right); } if (left < right) { generateParenthesis(results, prefix+")", left, right-1); } }
相关文章推荐
- 22.Generate Parentheses (String; dfs)
- leetcode-22 Generate Parentheses
- Leetcode 22 Generate Parentheses
- [Java]LeetCode22 Generate Parentheses
- [leedcode 22] Generate Parentheses
- LeetCode 22 Generate Parentheses
- leetcode 22 Generate Parentheses
- Java [leetcode 22]Generate Parentheses
- leetcode-22-Generate Parentheses
- 22. Generate Parentheses
- 回溯之Leetcode22 Generate Parentheses
- LeetCode-22-Generate Parentheses(DFS/递归)-Medium
- 22. Generate Parentheses
- LeetCode 22-Generate Parentheses
- [leetcode 22] Generate Parentheses
- [LeetCode 22] Generate Parentheses
- LeetCode 22 Generate Parentheses
- [LeetCode-Algorithms-22] "Generate Parentheses" (2017.10.25-WEEK8)
- Leetcode 22 Generate Parentheses
- LeetCode 22:Generate Parentheses