Simple recursive solution. What is wrong with this?


  • 0
    M
    class Solution {
    public:
        vector<string> generateParenthesis(int n) {
            vector<string> ans;
            if(n<=0) return ans;
            if(n==1)
            {
                ans.push_back("()");
                return ans;
            }
            
            vector<string> res= generateParenthesis(n-1);
            
            for(int i=0; i<res.size(); i++)
            {
                string temp=res[i];
                ans.push_back( "("+temp+")" );
                ans.push_back( temp+"()" );
                if(  "()"+temp != ans.back() )
                ans.push_back("()"+temp);
                
            }
            return ans;
        }
    };

  • 1
    Z

    Hi, this solution is incorrect. For example, when n = 3:

    You have : "((()))", "(()())", "(())()", "()(())", "()()()"

    From above, you cannot get (())(()) by your solution for you simply add (elem), ()elem, elem().


  • 0
    M

    My code is similar to yours. But can not pass the test either.


Log in to reply
 

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