Recursion 8.5

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  ----------
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值