题解 | #括号生成#

括号生成

https://www.nowcoder.com/practice/c9addb265cdf4cdd92c092c655d164ca

class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param n int整型
     * @return string字符串vector
     */
    string left = "(";
    string right = ")";
    vector<string> res;
    void pro(int n, int x, int y, string str, int num) {
        if (y > x) return;
        if (x == y && x + y == 2*n) {
            if(std::find(res.begin(), res.end(), str) == res.end()) res.push_back(str);
        }
        if (x + y < 2*n) {
            if (x <= y) {
                pro(n, x + 1, y, (str + left), num - 1);
            } else if (x > y) {
                if (x < n) {
                    pro(n, x + 1, y, str + left, num - 1);
                }
                pro(n, x, y + 1, str + right, num - 1);
            }
        }
    }

    vector<string> generateParenthesis(int n) {
        // write code here
        // 只要每时每刻满足左边括号的数目是大于右边括号的数目即可
        string str;
        pro(n, 0, 0, str, 2*n);
        return res;
    }
};

全部评论

相关推荐

点赞 评论 收藏
分享
05-12 22:16
已编辑
北京邮电大学 研发工程师
牛客302360988号:0offer+1 滴滴都不给我面 佬没投鹅吗,鹅应该很喜欢北邮吧
投递美团等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务