[LeetCode]--22. 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:[ "((()))", "(()())", "(())()",

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:

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

用二叉树形象的表示这种关系。然后再把二叉树转化为代码的形式。因为二叉树的定义就是递归定义的,因此本题很明显应该使用递归的形式。

这里写图片描述

就如同遍历查找一棵二叉树一样,只不过这个是一个个往上加。

public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<String>();
        if (n == 0)
            return res;
        dfs(res, "", n, n);
        return res;
    }

    private void dfs(List<String> res, String tem, int left, int right) {
        if (0 == left && 0 == right) {
            res.add(tem);
            return;
        } else if (left > 0)
            dfs(res, tem + '(', left - 1, right);
        if (left < right)
            dfs(res, tem + ')', left, right - 1);
    }

这种递归到最后自然就都加上去了。

目录
相关文章
LeetCode 301. Remove Invalid Parentheses
删除最小数量的无效括号,使得输入的字符串有效,返回所有可能的结果。 说明: 输入可能包含了除 ( 和 ) 以外的字符。
56 0
LeetCode 301. Remove Invalid Parentheses
LeetCode 241. Different Ways to Add Parentheses
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。
59 0
LeetCode 241. Different Ways to Add Parentheses
Leetcode-Easy 20. Valid Parentheses
Leetcode-Easy 20. Valid Parentheses
94 0
Leetcode-Easy 20. Valid Parentheses
LeetCode 20:有效的括号 Valid Parentheses
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 有效字符串需满足: 左括号必须用相同类型的右括号闭合。
745 0
|
C++ 机器学习/深度学习