22. Generate Parentheses

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 class Solution {
 2     public void dfs(int leftp, int remain, char[] s, int pos, List ans, int n) {
 3         if (pos == s.length ) {
 4             if (remain == 0)
 5                 ans.add(String.valueOf(s));
 6             return;
 7         }
 8         if (leftp < n) {
 9             s[pos] = '(';
10             dfs(leftp + 1, remain + 1, s, pos + 1, ans, n);
11         }
12         if (remain > 0) {
13             s[pos] = ')';
14             dfs(leftp, remain - 1, s, pos + 1, ans, n);
15         }
16     }
17     public List generateParenthesis(int n) {
18         List ans = new ArrayList<>();
19         char[] s = new char[2 * n];
20         dfs(0, 0, s, 0, ans, n);
21         return ans;
22         
23     }
24 }

 

你可能感兴趣的:(22. Generate Parentheses)