C++ solution by using recursion


  • 0
    K
    #include <vector>
    #include <iostream>
    #include <string>
    using namespace std;
    class Solution {
    public:
        vector<string> generateParenthesis(int n) {
         vector<string> vec_res;
         help(n,n,vec_res,"");
         return vec_res;
        }
        void help(int left_n,int right_n,vector<string>& res,string current){
         if(left_n ==0&&right_n==0){
          res.push_back(current);
          return;
         }
         if(left_n==0){
          help(left_n,right_n-1,res,current+")");
          return;
         }
         if(left_n>0&&right_n>0&&left_n==right_n){
           help(left_n-1,right_n,res,current+"(");
           return;
         }
         help(left_n-1,right_n,res,current+"(");
         help(left_n,right_n-1,res,current+")");
         return;
        }
    };
    

Log in to reply
 

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