标签:leetcode generate parentheses
Generate Parentheses:
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
class Solution { public: int left; int right; int len; vector<string> ret; void getAllParenthesis(<strong><span style="color:#ff0000;">string& str</span></strong>, int left, int right){ if(left+right==2*len){ ret.push_back(str); return ; } if(left<len){ <span style="color:#ff6666;"> </span><span style="color:#ff0000;">str.push_back('(')</span><span style="color:#ff6666;">;//字符串可以直接使用push_back,pop_back函数</span> getAllParenthesis(str, left+1, right); <span style="color:#ff0000;">str.pop_back();</span> } if(right<left){ <span style="color:#ff0000;"> str.push_back(')');</span> getAllParenthesis(str, left, right+1); <span style="color:#ff0000;"> str.pop_back();</span> } } vector<string> generateParenthesis(int n) { if(n<=0) return ret; len=n; string str; getAllParenthesis(str, 0, 0); return ret; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:leetcode generate parentheses
原文地址:http://blog.csdn.net/jisuanji_wjfioj/article/details/46731149