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 public class Solution {
 2     public List<String> generateParenthesis(int n) {
 3         List<String> result = new ArrayList<>();
 4         if (n <= 0) {
 5             return result;
 6         }
 7         String parenthesis = new String();
 8         helper(result, parenthesis, n, n);
 9         return result;
10     }
11     
12     private void helper(List<String> result, String parenthesis, int left, int right) {
13         if (left == 0 && right == 0) {
14             result.add(parenthesis);
15             return;
16         }
17         if (left > 0) {
18             helper(result, parenthesis + "(", left - 1, right);
19         }
20         if (right > 0 && left < right) {
21             helper(result, parenthesis + ")", left, right - 1);
22         }
23 
24     }
25 }

 

posted @ 2016-04-24 18:49  YuriFLAG  阅读(110)  评论(0)    收藏  举报