标签:
Given n pairs of parentheses, write a function togenerate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))","(()())", "(())()", "()(())", "()()()"
HideTags
#pragma once #include<iostream> #include<sstream> #include<string> #include<vector> using namespace std; //将数组temp中字符合成字符串push进result void pushto(char* temp, int n, vector<string> &result) { string s; stringstream ss; for (int i = 0; i < n; i++) ss << temp[i]; result.push_back(ss.str()); } //now:temp当前要赋值的位置 void generateandpush(char *temp, vector<string> &result,int now,int n,int count) { if (count < 0)//此路不通 return; if (now == n) { if (count==0)//最后,净左括号数应为0 pushto(temp, n, result); return; } temp[now] = '('; count++; generateandpush(temp, result, now + 1, n,count); count--;//恢复 temp[now] = ')'; count--; generateandpush(temp, result, now + 1, n,count); return; } vector<string> generateParenthesis(int n) { char *temp = new char[2*n];//n对 vector<string> result; int count = 0;//记录 左括号-右括号 generateandpush(temp, result,0,2*n,count); return result; } void main() { vector<string> result; result = generateParenthesis(3); for (int i = 0; i < result.size(); i++) //printf("%s", result[0].c_str());//注意printf打印string时要用:s.c_str() cout << result[i] << ' '; cout << endl; system("pause"); }
标签:
原文地址:http://blog.csdn.net/hgqqtql/article/details/43707557