[LeetCode]Generate Parentheses

class Solution {
public:
	void generateParenthesis_aux(vector<int>& remainNum, stack<char>& stackPath, 
		string& path, vector<string>& ans)
	{
		if(remainNum[0] == 0 && remainNum[1] == 0)
		{
			ans.push_back(path);
			return;
		}

		if(remainNum[0] > 0)//push '('
		{
			remainNum[0]--; path.push_back('('); stackPath.push('(');
			generateParenthesis_aux(remainNum, stackPath, path, ans);
			remainNum[0]++; path.pop_back(); stackPath.pop();
		}

		if(remainNum[1] > 0 
			&& !stackPath.empty() 
			&& stackPath.top() == '(')//pop '('
		{
			remainNum[1]--; path.push_back(')'); stackPath.pop();
			generateParenthesis_aux(remainNum, stackPath, path, ans);
			remainNum[1]++; path.pop_back(); stackPath.push('(');
		}

	}
	vector<string> generateParenthesis(int n) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		string path;
		vector<string> ans;
		vector<int> remainNum(2, n);
		stack<char> stackPath;
		generateParenthesis_aux(remainNum, stackPath, path, ans);
		return ans;
	}
};

second time

class Solution {
public:
    void generateParenthesisUtil(int leftNum, int rightNum, string& curPath, stack<char>& curStack, vector<string>& allPaths)
    {
        if(leftNum == 0 && rightNum == 0 && curStack.size() == 0)
        {
            allPaths.push_back(curPath);
            return ;
        }
        
        if(leftNum >= 1)
        {
            curPath.push_back('(');
            curStack.push('(');
            generateParenthesisUtil(leftNum-1, rightNum, curPath, curStack, allPaths);
            curStack.pop();
            curPath.pop_back();
        }
        if(rightNum >= 1 && curStack.size() >= 1)
        {
            curPath.push_back(')');
            curStack.pop();
            generateParenthesisUtil(leftNum, rightNum-1, curPath, curStack, allPaths);
            curStack.push('(');
            curPath.pop_back();
        }
    }
    vector<string> generateParenthesis(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        string curPath;
        stack<char> curStack;
        vector<string> allPaths;
        generateParenthesisUtil(n, n, curPath, curStack, allPaths);
        return allPaths;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI记忆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值