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:
"((()))", "(()())", "(())()", "()(())", "()()()"DFS
Solution:
1: public class Solution {
2: public ArrayList<String> generateParenthesis(int n) {
3: ArrayList<String> result=new ArrayList<String>();
4: DoDSF("",n,n,result);
5: return result;
6: }
7: private void DoDSF(String prefix, int left, int right, ArrayList<String> result)
8: {
9: if(left==0&& right==0)
10: {
11: result.add(prefix);
12: return;
13: }
14: if(left!=0)
15: DoDSF(prefix+"(",left-1,right,result);
16: if(left<right)
17: DoDSF(prefix+")",left,right-1,result);
18: return;
19: }
20: }
没有评论:
发表评论