LeetCode 笔记系列五 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:

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

解法:leetcode上的解法很赞。 其实这也是利用的递归的分支。构建了一树状结构并遍历,叶子节点就是valid的结果。

 1 public static ArrayList<String> generateParenthesis(int n) {
 2         // Start typing your Java solution below
 3         // DO NOT write main() function
 4         ArrayList<String> result = new ArrayList<String>();
 5         generate(result, "",0,0,n);
 6         return result;
 7     }
 8     
 9     private static void generate(ArrayList<String> result, String prefix, int leftCount, int rightCount,int totalPairs){
10         if(leftCount == totalPairs){
11             for(int i = 0; i < totalPairs - rightCount;i++){
12                 prefix += ")";
13             }
14             result.add(prefix);
15             return;
16         }
17         generate(result, prefix + "(", leftCount + 1, rightCount, totalPairs);
18         if(leftCount > rightCount) generate(result, prefix +")", leftCount, rightCount + 1,totalPairs);
19     }
View Code

leftCount和rightCount分别记录当前高度(或者长度)中,“(“和“)”的数目。如果leftCount等于了总共要求的括号对数,我们就把剩余的右括号添加进去并作为一个结果记录下来。这个有一些类似二叉树的post order遍历。

值得学习的地方:

1.利用递归模拟组合操作,做有序搜索;

2.有效的算法来自简单的代码。

posted on 2013-07-04 17:56  lichen782  阅读(1087)  评论(0编辑  收藏  举报