您的位置:首页 > 其它

Generate Parentheses 生成有意义的括号对

2014-10-23 22:04 441 查看
Question:

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:

"((()))", "(()())", "(())()", "()(())", "()()()"。

思想:
1. 采用递归,解决此题。
2. 递归条件:剩下的'('的数要<=')'的数量,且两者的剩余数量都要大于等0,这样才能保证‘()’的匹配。

代码:

public class Solution {
public List<String> generateParenthesis(int n) {
List<String> myResult = new ArrayList<String>();
String transfer = "";
process(n, n, (ArrayList<String>)myResult, transfer);
return myResult;
}
public static void process(int left, int right, ArrayList<String>  myResult, String transfer){
if(left == 0 && right == 0) myResult.add(transfer); // add to myResult
if(left <= right && left>0)
process(left-1, right, myResult,(transfer + '(') ); // make sure left>=0
if(left < right && left>=0 )
process(left, right-1, myResult, (transfer + ')') ); // right-1>=left
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: