Leetcode-22

题目22.括号生成

难度:中等

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 **有效的 **括号组合。

示例 1:

输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]

示例 2:

输入:n = 1
输出:["()"]

提示:

  • 1 <= n <= 8

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

dfs,左右子树为(),刚好对应二叉树结构

解题代码

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> res;
        if (n <= 0) return res;
        dfs(n, "", res, 0, 0);
        return res;
    }

    void dfs(int n, string path, vector<string>& res, int open, int close) {
        if (open > n || close > open) return;

        if (path.length() == 2 * n) {
            res.push_back(path);
            return;
        }

        dfs(n, path + "(", res, open + 1, close);
        dfs(n, path + ")", res, open, close + 1);
    }
};
posted @ 2024-06-10 15:18  tianwen42  阅读(45)  评论(0)    收藏  举报