LeetCode题解:Generate Parentheses

来源:互联网 发布:淘宝盖楼怎么才能中 编辑:程序博客网 时间:2024/05/21 17:09

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:

“((()))”, “(()())”, “(())()”, “()(())”, “()()()”

题意:求给定n对原括号的组合可能数

解题思路:卡特兰数

代码:

public class Solution {    public List<String> generateParenthesis(int n) {        List<String> result = new ArrayList<String>();        generate(result, "", 0, 0, n);        return result;    }    private void generate(List<String> result, String str, int left, int right, int n){        if(left == n){            for(int i = 0; i < n - right; i++){                str += ")";            }            result.add(str);            return;        }        generate(result, str + "(", left + 1, right, n);        if(left > right){            generate(result, str + ")", left, right + 1, n);        }    }}
0 0
原创粉丝点击