Leetcode: Generate Parentheses
2014-11-05 16:08
363 查看
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:
Store the remaining number of '(' and ')', and the remaining number of '(' should be less than ')' to form a valid parenthesis. Use recursion to do this. Time complexity
is O(number of results). The number of results can be calculated using Catalan number.
public class Solution {
public ArrayList<String> generateParenthesis(int n) {
ArrayList<String> res = new ArrayList<String>();
if (n <= 0) {
return res;
}
StringBuilder sb = new StringBuilder();
helperParenthesis(n, n, res, sb);
return res;
}
private void helperParenthesis(int l, int r, ArrayList<String> res, StringBuilder sb) {
if (l > r) {
return;
}
if (l == 0 && r == 0) {
res.add(sb.toString());
}
if (l > 0) {
helperParenthesis(l - 1, r, res, sb.append('('));
sb.deleteCharAt(sb.length() -1);
}
if (r > 0) {
helperParenthesis(l, r - 1, res, sb.append(')'));
sb.deleteCharAt(sb.length() -1);
}
}
}
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
Store the remaining number of '(' and ')', and the remaining number of '(' should be less than ')' to form a valid parenthesis. Use recursion to do this. Time complexity
is O(number of results). The number of results can be calculated using Catalan number.
public class Solution {
public ArrayList<String> generateParenthesis(int n) {
ArrayList<String> res = new ArrayList<String>();
if (n <= 0) {
return res;
}
StringBuilder sb = new StringBuilder();
helperParenthesis(n, n, res, sb);
return res;
}
private void helperParenthesis(int l, int r, ArrayList<String> res, StringBuilder sb) {
if (l > r) {
return;
}
if (l == 0 && r == 0) {
res.add(sb.toString());
}
if (l > 0) {
helperParenthesis(l - 1, r, res, sb.append('('));
sb.deleteCharAt(sb.length() -1);
}
if (r > 0) {
helperParenthesis(l, r - 1, res, sb.append(')'));
sb.deleteCharAt(sb.length() -1);
}
}
}
相关文章推荐
- LeetCode: Generate Parentheses
- [LeetCode] 022. Generate Parentheses (Medium) (C++/Java/Python)
- 【leetcode】Generate Parentheses
- [leetcode] Generate Parentheses
- [LeetCode]022-Generate Parentheses
- 【leetcode】Generate Parentheses
- leetcode之 Generate Parentheses
- [Leetcode] #22 Generate Parentheses
- [Leetcode] Generate Parentheses
- [leetcode javascript解题]Generate Parentheses
- LeetCode Generate Parentheses
- [LeetCode] Generate Parentheses
- [leetcode] Generate Parentheses
- leetcode-22 Generate Parentheses
- LeetCode 22 -Generate Parentheses ( JAVA )
- 【leetcode】GenerateParentheses
- 【Leetcode】Generate Parentheses in JAVA
- leetcode 日经贴,Cpp code -Generate Parentheses
- [leetcode]Generate Parentheses
- [LeetCode] Generate Parentheses