22.Generate Parentheses

Givennpairs of parentheses, write a function togenerate all combinations of well-formed parentheses.

For example, givenn= 3, a solution set is:

"((()))","(()())", "(())()", "()(())", "()()()"

HideTags

BacktrackingString

#pragma once#include<iostream>#include<sstream>#include<string>#include<vector>using namespace std;//将数组temp中字符合成字符串push进resultvoid 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)//最后,,净左括号数应为0pushto(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");}

旅游时最好的习惯:找个舒适的小店,挑张雅致的明信片,

22.Generate Parentheses

相关文章:

你感兴趣的文章:

标签云: