您的位置:首页 > 其它

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);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode