码迷,mamicode.com
首页 > 其他好文 > 详细

22.Generate Parentheses

时间:2015-02-10 23:18:29      阅读:396      评论:0      收藏:0      [点我收藏+]

标签:

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

 Backtracking String


#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");
}

 

22.Generate Parentheses

标签:

原文地址:http://blog.csdn.net/hgqqtql/article/details/43707557

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!