LeetCode HOT100 - 括号生成

感觉就是搜索

依据当前剩余的左括号和右括号判断怎么添加是合适的

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> ans;
        auto dfs = [&](auto self, int x, int y, string s) -> void {
            if (x == 0 && y == 0) {
                ans.emplace_back(s);
                return;
            }
            if (x == y) {
                self(self, x - 1, y, s + "(");
                return;
            }
            if (x == 0) {
                self(self, x, y - 1, s + ")");
                return;
            }
            self(self, x, y - 1, s + ")");
            self(self, x - 1, y, s + "(");
        };
        dfs(dfs, n, n, "");
        return ans;
    }
};

看题解还有回溯甚至动规的,下次再补了

posted @ 2026-04-09 12:47  rdcamelot  阅读(18)  评论(0)    收藏  举报