括号有效组合(循环递归)

括号有效组合(循环递归)

问题描述如下:

给定一个整数 n,求有 n 个括号的组合有哪些?

如 n = 3,可能的括号有效组合包括:( )( )( ),( )( ( ) ),( ( ( ) ) ),( ( ) )( ),( ( ) ( ) )

分析:

在这里插入图片描述
我们可以通过在当前 n 层中对每个元素进行 ”左“,”右“,”中 “ 三种操作得到 n+1 层的括号组合。

注意可能会出现重复,因此要使用集合 set 来去重。

参考代码:

#include<iostream>
#include<set>
using namespace std;

set<string> parent;

// 利用set的去重以及递归来求解 O(n^2)
void getResult(int n, set<string> &parentSet){
	// 出口 
	if(n == 1){
		parentSet.insert("()");
		return;
	}
	// 递归先获得n-1层的括号组合 
	set<string> subParent;
	getResult(n-1, subParent);
	// 对n-1层的每个元素在前后中加上括号保存在n层 
	for(set<string>::iterator it = subParent.begin(); it != subParent.end(); it++){
		parentSet.insert("()"+*it);
		parentSet.insert(*it+"()");
		parentSet.insert("("+*it+")");
	}
}

int main(){
	int n;
	while(cin >> n){
		parent.clear();
		getResult(n);
		int first = 1;
		for(set<string>::iterator it = parent.begin(); it != parent.end(); it++){
			if(first) first = 0;
			else cout << " ";
			cout << *it;	
		}
		cout << endl;
	}
	return 0;
} 

【END】感谢观看

发布了44 篇原创文章 · 获赞 17 · 访问量 9113

猜你喜欢

转载自blog.csdn.net/qq_41765114/article/details/88406858
今日推荐