c++ DFS solution


  • 0
    class Solution {
    public:
      vector<string> generateParenthesis(int n) {
        vector<string> ret;
        if (n > 0)
        {
          dfs(ret, n, n, "");
        }
        return ret;
      }
      void dfs(vector<string> &ret, int  p, int q, string str)
      {
        if (p == 0 && q == 0)
        {
          ret.push_back(str);
        }
        if (p > 0)
        {
          dfs(ret, p - 1, q, str + "(");
        }
        if (q > 0 && q > p)
        {
          dfs(ret, p, q - 1, str + ")");
        }
      }
    };
    

Log in to reply
 

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