LeetCode-----第二十二题-----括号生成

括号生成

难度:中等

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

 

示例:

输入:n = 3
输出:[
       "((()))",
       "(()())",
       "(())()",
       "()(())",
       "()()()"
     ]

 

题目解析:

       经典回溯法,判断情况就是两种“(”还是“)”。每次添加好就pop回溯。结束和边界条件就是添加满了。

 

参考代码:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
#include <list>
#include <unordered_map>
#include <cstring>
#include <map>
#include <stdexcept>

using namespace std;

class Solution {
public:
	vector<string> generateParenthesis(int n) {
		vector<string> res;
		if (n <= 0)
			return res;

		Backtrack(res,n,0,0,"");
		return res;
	}

	void Backtrack(vector<string>& res, int n, int i, int j, string result)
	{
        //结束及边界条件
		if (2 * n == result.size())
		{
			if (!result.empty() && check(result))
				res.push_back(result);
			return;
		}
        //单括号的数目小于n
		if (i < n)
		{
			result.push_back('(');
			Backtrack(res, n, i + 1, j, result);
			result.pop_back();
		}
		if (j < n)
		{
			result.push_back(')');
			Backtrack(res, n, i, j + 1, result);
			result.pop_back();
		}
	}
    //判断添加的括号是否符合标准
	bool check(const string& str)
	{
		if (str.empty())
			return true;
		stack<char> my_stack;
		my_stack.push(str[0]);

		for (int i = 1; i < str.size(); i++)
		{
			if (!my_stack.empty() && my_stack.top() == '(' && str[i] == ')')
			{
				my_stack.pop();
			}
			else
			{
				my_stack.push(str[i]);
			}
		}
		if (my_stack.empty())
			return true;
		else
			return false;
	}
};

int main()
{
	Solution solution;
	vector<string> res;

	res = solution.generateParenthesis(3);

	if (!res.empty())
	{
		for (int i = 0; i < res.size(); i++)
		{
			cout << res[i] << endl;
		}
	}

	system("pause");
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值