您的位置:首页 > 其它

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.

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