其他分享
首页 > 其他分享> > 力扣-22-括号生成

力扣-22-括号生成

作者:互联网

直达链接

之前好像也有一道括号的题,力扣-20-有效的括号,给的标签是“栈”,不过这次的标签是“动态规划”和“回溯法”了

返回所有可能结果,一看就是回溯了,但是我好像一直没完全搞明白过

class Solution {
public:

	void backtrack(vector<string>& ans, string& cur, int open, int close, int n) {
		if (cur.size() == n * 2) {
			ans.push_back(cur);
			return;
		}
		if (open < n) {
			cur.push_back('(');
			backtrack(ans, cur, open + 1, close, n);
			cur.pop_back();
		}
		if (close < open) {
			cur.push_back(')');
			backtrack(ans, cur, open, close + 1, n);
			cur.pop_back();
		}
	}

	vector<string> generateParenthesis(int n) {
		vector<string> result;
		string current;
		backtrack(result, current, 0, 0, n);
		return result;
	}
};

标签:cur,22,backtrack,int,back,力扣,括号,ans,open
来源: https://www.cnblogs.com/yaocy/p/16561713.html