标签:
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
思路:两个dfs函数,互相调用
class Solution { public: vector<string> generateParenthesis(int n) { if(n == 0) return ret; len = n*2; dfsLeft(n, 0, ""); return ret; } void dfsRight(int lNum, int rNum, string str){//add right parenthese while(rNum){ str += ‘)‘; dfsLeft(lNum, --rNum, str); } if(str.length() == len){ ret.push_back(str); } } void dfsLeft(int lNum, int rNum, string str){//add left parenthese while(lNum){ str += ‘(‘; dfsRight(--lNum, ++rNum, str); } } private: int len; vector<string> ret; };
22.Generate Parentheses (String; dfs)
标签:
原文地址:http://www.cnblogs.com/qionglouyuyu/p/4705551.html