c++ (0 ms)


  • 0
    class Solution {
      public:
        void bt(int open, int close, const string& str, int n, vector<string>& ans) {
          if (str.size() == n * 2) {
            ans.push_back(str);
            return;
          }
          if (open > n - 1) {
            bt(open, close + 1, str + ")", n, ans);
          } else if (open > close) {
            bt(open + 1, close, str + "(", n, ans);
            bt(open, close + 1, str + ")", n, ans);
          } else {
            bt(open + 1, close, str + "(", n, ans);
          }
        }
        vector<string> generateParenthesis(int n) {
          vector<string> ans;
          string str = "";
          bt(0, 0, str, n, ans);
          return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.