22.生成括号

版权声明:只要梦想一天,只要梦想存在一天,就可以改变自己的处境。 https://blog.csdn.net/dongyanwen6036/article/details/85267585

n {n} 组括号,括号字符串长度为 2 n {2n} ,字符串中的每个字符有两种选择可能,“(”“)”,故有 2 2 n 2^{2n} 种可能。
在这里插入图片描述

分析[1]:我们定义两个变量left和right分别表示剩余左右括号的个数,如果在某次递归时,左括号的个数大于右括号的个数,说明此时生成的字符串中右括号的个数大于左括号的个数,即会出现'())'或者‘)(’这样的非法串,所以这种情况直接返回,不继续处理。如果left和right都为0,则说明此时生成的字符串已有n个左括号和n个右括号,且字符串合法,则存入结果中后返回。如果以上两种情况都不满足,若此时left大于0,则调用递归函数,注意参数的更新,若right大于0,则调用递归函数,同样要更新参数。
c++ code DFS:

 class Solution {
 public:
	 void Generaterecurse(int Restleft, int Restright, string str, vector<string>&res)
	 {
		 if (Restleft >Restright)return;//会出现())
		 if (Restleft == 0 && Restright == 0)
			 res.push_back(str);
		 if (Restleft > 0)Generaterecurse(Restleft - 1, Restright, str + '(', res);
		 if(Restright>0)Generaterecurse(Restleft, Restright-1, str + ')', res);
	 }
	 vector<string> generateParenthesis(int n) {
		 vector<string>res;
		 Generaterecurse(n, n, "",res);
		 return res;
	 }
 };

[1]https://www.cnblogs.com/grandyang/p/4444160.html

猜你喜欢

转载自blog.csdn.net/dongyanwen6036/article/details/85267585
今日推荐