Concise backtracking C++ solution


  • 0
    B
    class Solution {
    public:
       void Generate(vector<string> & ret, string cur, int n, int depth, int pos)
    {
    	if (depth == n && pos == 0)
    	{
    		ret.push_back(cur);
    		return;
    	}
    	else if (depth == n && pos != 0)
    	{
    		return;
    	}
    	else if (pos < 0)
    	{
    		return;
    	}
    	else
    	{
    		Generate(ret, cur + "(", n, depth + 1, pos + 1);
    		Generate(ret, cur + ")", n, depth + 1, pos - 1);
    	}
    }
    vector<string> generateParenthesis(int n) {
    	vector<string> ret;
    	string cur;
    	int depth = 0;
    	int pos = 0;
    	Generate(ret, cur, 2*n, depth, pos);
    	return ret;
    }
    
    };
    

Log in to reply
 

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