【墨鳌】【位运算】【01枚举】

题目链接
题解链接

解题思路

  • 简单 01 枚举
  • 位运算基础操作
class Solution {
private:
    bool isValid(string s) {
        int count = 0;
        for (char &c: s) {
            if (c == '(')count++;
            else count--;
            if (count < 0)return false;
        }
        return count == 0;
    }

public:
    vector<string> generateParenthesis(int n) {
        vector<string> ans;
        for (int mask = 0; mask < (1 << (n * 2)); mask++) {
            string s = "";
            for (int i = 0; i < (n * 2); i++) {
                if (mask & (1 << i))s += '(';
                else s += ')';
            }
            if (isValid(s))ans.push_back(s);
        }
        return ans;
    }
};
posted @ 2022-02-26 17:26  墨鳌  阅读(20)  评论(0编辑  收藏  举报