题目描述:
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:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
代码:
#include<iostream>
#include<vector>
using namespace std ;
void show_vector_char(vector<char> & aim)
{
for(int i =0 ;i<aim.size() ;i++)
cout<<aim[i] ;
cout<<endl ;
return ;
}
enum {right = 1};
bool judge_fitness(vector<char>& aim)
{
int sum = 0 ;
for(int i =0 ;i<aim.size() ;i++)
{
if(aim[i]=='(')
sum++ ;
else
sum-- ;
if(sum <0 )
break ;
}
if(sum == 0)
return true ;
else
return false ;
}
void generate(vector<vector<char> >& result, int left_or_right , int n ,
int aim_len ,vector<char>&last)
{
if(aim_len == n)
return ;
if(left_or_right == 1)
last.push_back(')') ;
else
last.push_back('(') ;
if(n == (aim_len-1))
{
if(judge_fitness(last) == true)
{
result.push_back(last) ;
//show_vector_char(last) ;
}
}
vector<char>last1 ;
vector<char>last2 ;
last1 = last ; last2 = last ;
generate(result,0 ,n+1,aim_len,last1) ;
generate(result,1,n+1,aim_len,last2) ;
return ;
}
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result_string ;
vector<vector<char> >result ;
vector<char>last1 ;
vector<char>last2 ;
generate(result,0,0,n*2,last1) ;
generate(result,1,0,n*2,last2) ;
string tem ;
for(int i =0 ;i<result.size() ;i++)
{
tem.clear() ;
for(int j = 0 ;j<result[i].size() ;j++)
tem.push_back(result[i][j]) ;
result_string.push_back(tem) ;
}
return result_string ;
}
};
int main(void)
{
Solution solution ;
solution.generateParenthesis(3) ;
}