My 3ms C++ Solution using backtracking


  • 0
    G
    class Solution {
    public:
        string tmp;
        void backTrack(int sum,int n,int m,vector<string>& ans) {
            if (!m) {
                ans.push_back(tmp);
                return;
            }
            if (n) {
                tmp.push_back('(');
                backTrack(sum+1,n-1,m-1,ans);
                tmp.pop_back();
            }
            if (sum) {
                tmp.push_back(')');
                backTrack(sum-1,n,m-1,ans);
                tmp.pop_back();
            }
        }
        vector<string> generateParenthesis(int n) {
            vector<string> ans;
            tmp="";
            backTrack(0,n,n<<1,ans);
            return ans;
        }
    };

Log in to reply
 

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