标签:style class blog code http color
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, 采用递归的方式进行,比较难把握的是每次递归的结果用什么来存储,终止条件是什么。
需要注意的是,在每次递归的时候剩余左括号不可能比右括号多,否则就终止。
1 class Solution { 2 public: 3 vector<string> vi; 4 void generateOne(int left,int right,string s) 5 { 6 if(left==0) 7 { 8 vi.push_back(s+string(right,‘)‘)); 9 return ; 10 } 11 if(left>=right) 12 generateOne(left-1,right,s+‘(‘); 13 else 14 { 15 generateOne(left-1,right,s+‘(‘); 16 generateOne(left,right-1,s+‘)‘); 17 } 18 } 19 vector<string> generateParenthesis(int n) { 20 int left=n,right=n; 21 vi.clear(); 22 generateOne(n,n,""); 23 return vi; 24 } 25 };
转载请注明出处: http://www.cnblogs.com/double-win/ 谢谢!
LeetCode: Generate Parentheses 题解,布布扣,bubuko.com
LeetCode: Generate Parentheses 题解
标签:style class blog code http color
原文地址:http://www.cnblogs.com/double-win/p/3793021.html