[LeetCode 22] 括号生成

22. 括号生成

dfs+剪枝

本题使用dfs搜索,选(或者)两个分支。
观察出剪枝条件:不管进行到哪一位,(的数量都是>=)的,而且数量都不能超过n

#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
 
class Solution {
  public:
    void dfs(int i, int n, int left, int right, vector<string> &res,
             string str) {
        //剪枝条件
        if (left < right || left > n)
            return;
        if (i >= 2 * n) {
            res.push_back(str);
            return;
        }

        str += '(';
        dfs(i + 1, n, left + 1, right, res, str);
        str[str.length() - 1] = ')';
        dfs(i + 1, n, left, right + 1, res, str);
    }
    vector<string> generateParenthesis(int n) {
        vector<string> res;
        string str;
        int left = 0, right = 0;
        dfs(0, n, left, right, res, str);
        return res;
    }
};

int main() {
    Solution s;
    vector<string> res;
    res = s.generateParenthesis(3);
    for (int i = 0; i < res.size(); i++) {
        cout << res[i] << endl;
    }

    cout << endl << res.size();

    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 题目描述: 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出...
    LeeYunFeng阅读 5,135评论 0 50
  • 题目 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出 n ...
    半亩房顶阅读 2,801评论 0 1
  • 1、题目 22. 括号生成 - 力扣(LeetCode) https://leetcode-cn.com/prob...
    风卷晨沙阅读 3,914评论 0 0
  • 题目 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出 n ...
    禾木清清阅读 1,267评论 0 0
  • 文|王不二 一、 电脑屏幕上闪着荧荧的光映在胡林脸上,时而红,时而蓝,无休止地混杂变换着。 胡林用凹凸不平又藏满污...
    旅人还有平凡阅读 3,793评论 12 35