【Leetcode】22.Generate Parentheses【DFS】

来源:互联网 发布:淘宝云客服报名入口 编辑:程序博客网 时间:2024/06/05 08:37

Given n pairs of parentheses, write a function to generate all combinations of well-formed parenth
eses.

For example, given n = 3, a solution set is:

[  "((()))",  "(()())",  "(())()",  "()(())",  "()()()"]
参考思路:http://blog.csdn.net/u012501459/article/details/46787097

如果这道题是求上面括号的组合有多少种方式,那么这是一道卡塔兰数的题目,最开始就陷入到这里了,按照卡塔兰数的思路找寻递归关系式,怎么也寻找不到,但这道题好像是另一类问题的一个标准模板,就是求解卡塔兰数的具体组合是什么样的,这又是一种通用的解法。

对于这道题,第一个肯定是’(‘,接下来即可以是’(‘也可以是’)’,只需要满足下面三条规则:

left:表示剩余左括号的数目
right:表示剩余右括号的数目

满足的条件如下:

  1. 当left=0&&right=0时表示找到一条路径
  2. 当left!=0时可以向左子树伸展
  3. 当right!=0&&left< right时可以向右子树伸展
代码:

public class Solution {    public List<String> generateParenthesis(int n) {        List<String> result = new ArrayList<String>();        if(n == 0) return result;        int left = n;        int right = n;        String path = "";        findRes(n,n,result,path);                return result;    }    private void findRes(int left, int right,List<String> result, String path){        if(left == 0 && right == 0){            result.add(path);            return;        }        if(left != 0) findRes(left-1, right, result, path+'(');        if(right != 0 && left < right) findRes(left, right-1, result, path+')');    }}




0 0