程序媛詹妮弗
终身学习

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:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

题意:  给定一个长度,生成所有此长度的合法括号序列。

 

Solution1:Backtracking.

We can observe that two constraints:

(1)  left Parentheses should come faster ahead to reach given n. 

(2) in each level, we increment left Parentheses count (or right Parentheses count) from given n, and add '(' (or ')') into path

At last, left and right Parentheses count become 0, we can gerenate a result path. 

 

code:

 1 /*
 2 Time:  O(2^n).
 3 Space: O(n).  use O(n) space to store the sequence(path) 
 4 */
 5 class Solution {
 6     public List<String> generateParenthesis(int n) {
 7         List<String> result = new ArrayList<>();
 8         if (n == 0) return result;
 9         helper("", n, n, result);
10         return result;
11 
12     }
13 
14     private void helper(String path, int left, int right, List<String> result) {
15         // corner
16         if (left > right) return;
17         // base
18         if (left == 0 && right == 0) {
19             result.add(path);
20             return;
21         }
22         if (left > 0) {
23             helper(path + "(", left - 1, right, result);
24         }
25         if (right > 0) {
26             helper(path + ")", left, right - 1, result);
27         }
28     }
29 }

 

posted on 2019-04-09 02:50  程序媛詹妮弗  阅读(178)  评论(0编辑  收藏  举报