c++ solution use backtrace


  • 0
    C
    class Solution {
    public:
        void generate(vector<string>& ans, char* str, int left,int right, int n, int idx){
            if( right == n ){
                str[idx] = '\0';
                ans.push_back(str);
                return;
            }
            if(left == right ){
                str[idx]='(';
                this->generate(ans, str, left+1, right, n, idx+1);
            }else if( right < n ){
                str[idx]=')';
                this->generate(ans, str, left, right+1, n, idx+1);
                if( left < n ){
                    str[idx]='(';
                    this->generate(ans, str, left+1, right, n, idx+1);
                }
            }
                
        }
        vector<string> generateParenthesis(int n) {
            vector<string> ans;
            char str[500];
            generate(ans, str, 0, 0, n, 0);
            return ans;
        }
    };
    

Log in to reply
 

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