22_括号的生成C++

方法一:生成一个树然后打印每条从根节点到叶节点的路径,其实比较麻烦。打印的时候需要判断叶节点是不是左括号

//define left parenthesis as -1, right parenthesis as 1
class Solution {
public:
	struct TreeNode {
		int val;
		TreeNode *left;
		TreeNode *right;
	};

	void generateTree(TreeNode* root, int parenthesis, int left,int right)
	{
		root->val = parenthesis;
		root->left = NULL;
		root->right = NULL;
		if (left > 0)
		{
			int templeft = left - 1;
			root->left = new TreeNode;
			generateTree(root->left, -1,templeft,right);
		}
		if (right > 0&&(right-1>=left))
		{
			int tempright = right - 1;
			root->right = new TreeNode;
			generateTree(root->right, 1, left, tempright);
		}
	}
	string int2Parenthesis(int val)
	{
		if (val == -1)
			return "(";
		if (val == 1)
			return ")";
	}
	//打印根节点到叶子节点
	vector<string> binaryTreePaths(TreeNode* root) {
		vector<string> ans;
		if (root == nullptr) return ans;
		queue<TreeNode*> q1;//用于层序遍历
		queue<string> q2;//用于存储路径
		TreeNode* T = root;
		string cur;
		cur = int2Parenthesis(T->val);
		q1.push(T);
		q2.push(cur);
		while (!q1.empty())
		{
			T = q1.front();
			q1.pop();
			if (T->left || T->right)
			{
				cur = q2.front();
				if (T->left)
				{
					q1.push(T->left);
					q2.push(cur + int2Parenthesis((T->left)->val));
				}
				if (T->right)
				{
					q1.push(T->right);
					q2.push(cur + int2Parenthesis((T->right)->val));
				}
				q2.pop();
			}
			else//叶子节点弹出
			{
				string tempPath = q2.front();
				if (tempPath.back() == ')')
				{
					ans.push_back(q2.front());
				}
				q2.pop();
			}
		}
		return ans;
	}

	vector<string> generateParenthesis(int n) {
		TreeNode* root = new TreeNode;
		generateTree(root, -1, n-1, n);
		vector<string> ans;
		ans = binaryTreePaths(root);
		return ans;
	}
};

方法二:回溯法。其实括号的生成过程只需要控制")“的数量小于等于”("的数量即可。递归中每次return之后回到外一层函数,下一步进行pop_back,则可腾出string末尾的括号位置,移至下一个分支。相当于实现了方法一中树的结构

using namespace std;
class Solution {
public:
	void backTrack(vector<string>& result, string & current, int open, int close, int n)
	{
		if (current.size() == n * 2)
		{
			result.push_back(current);
			return;
		}
		if (open < n)
		{
			current.append("(");
			backTrack(result, current, open + 1, close, n);
			current.pop_back();
		}
		if (close < open)
		{
			current.append(")");
			backTrack(result, current, open, close + 1, n);
			current.pop_back();
		}
	}
	vector<string> generateParenthesis(int n) {
		vector<string> ans;
		string cur;
		backTrack(ans, cur, 0, 0, n);
		return ans;
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值