My 0 ms simple recursive c++ solution


  • 0
    D
        int generate(int left, int right, string s, int n){
            
            if(left == n && right == n){
                ans.push_back(s);
            }
            else{
                int l = left;
                if(left<n)
                    generate(++left, right, s+"(", n);
                if(right<l)
                    generate(l, ++right, s+")", n);
            }
            return 0;
        }  
    
    
    
        vector<string> generateParenthesis(int n) {
            generate(0, 0, "", n);
            return ans;
        }

  • 3
    S

    I did a littel modification. Use left + 1 and right + 1 to avoid temp varaible l to make solution more readable.

    class Solution {
    public:
        vector<string> result;
        vector<string> generateParenthesis(int n) {
            generate(0, 0, "", n);
            return result;
        }
        void generate(int left, int right, string s, int n) {
            if(right == n) {
                result.push_back(s);
            }
            else
            {
                if(left < n)
                {
                    generate(left + 1, right, s + "(", n);
                }
                if(right < left)
                {
                    generate(left, right + 1, s + ")", n);
                }
            }
        }
    };

  • 0
    R

    right is always <= left
    so we can just use right to check

    if( right == n) {
    result.push_back(s);
    }


  • 0
    S

    You are right. I have edited my post.


Log in to reply
 

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