Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-pairs
// =====================================================================================
//
// Filename: 8_5.cpp
//
// Description: an algorithm to print all valid combinations of n-pairs of
// parentheses
//
// Version: 1.0
// Created: 2016/3/21 17:55:27
// Revision: none
// Compiler: g++
//
// Author:
// Organization:
//
// =====================================================================================
#include <iostream>
#include <list>
#include <string>
using namespace std;
void valid_parenthese(const std::string& prefix, int left, int right, std::list<std::string>& parentes_list) {
if(left==0){
std::string val(prefix);
val.append(right, ')');
parentes_list.push_back(val);
return;
}
int tmp = left;
std::string left_prefer(prefix);;
if(tmp>0){
left_prefer.append(1, '(');
valid_parenthese(left_prefer, --tmp, right, parentes_list);
}
std::string right_prefer(prefix);
if(right > left){
right_prefer.append(1, ')');
valid_parenthese(right_prefer, left, --right, parentes_list);
}
}
std::list<std::string> valid_parenthese(int pairs){
std::list<std::string> parentes_list;
if(pairs <=0) return parentes_list;
valid_parenthese("(", pairs -1, pairs, parentes_list);
return parentes_list;
}
// === FUNCTION ======================================================================
// Name: main
// Description:
// =====================================================================================
int main ( int argc, char *argv[] )
{
std::list<std::string> parentes_list;
const int N = 3;
parentes_list = valid_parenthese(N);
for(auto it = parentes_list.begin(); it!=parentes_list.end(); it++){
std::cout <<*it << std::endl;
}
return 0;
} // ---------- end of function main ----------