Finding all combinations of well-formed brackets

后端 未结 29 1604
盖世英雄少女心
盖世英雄少女心 2020-11-28 02:34

This came up while talking to a friend and I thought I\'d ask here since it\'s an interesting problem and would like to see other people\'s solutions.

The task is to

29条回答
  •  孤城傲影
    2020-11-28 03:01

    Not the most elegant solution, but this was how I did it in C++ (Visual Studio 2008). Leveraging the STL set to eliminate duplicates, I just naively insert new () pairs into each string index in every string from the previous generation, then recurse.

    #include "stdafx.h"
    #include 
    #include 
    #include 
    
    using namespace System;
    using namespace std;
    
    typedef set StrSet;
    
    void ExpandSet( StrSet &Results, int Curr, int Max )
    {
        if (Curr < Max)
        {
            StrSet NewResults;
    
            for (StrSet::iterator it = Results.begin(); it != Results.end(); ++it)
            {
                for (unsigned int stri=0; stri < (*it).length(); stri++)
                {
                    string NewStr( *it );
                    NewResults.insert( NewStr.insert( stri, string("()") ) );
                }
            }
            ExpandSet( NewResults, Curr+1, Max );
    
            Results = NewResults;
        }
    }    
    
    int main(array ^args)
    {
        int ParenCount = 0;
    
        cout << "Enter the parens to balance:" << endl;
        cin  >> ParenCount;
    
        StrSet Results;
        Results.insert( string("()") );
    
        ExpandSet(Results, 1, ParenCount);
    
        cout << Results.size() << ": Total # of results for " << ParenCount << " parens:" << endl;
    
        for (StrSet::iterator it = Results.begin(); it != Results.end(); ++it)
        {
            cout << *it << endl;
        }
    
    
        return 0;
    }
    

提交回复
热议问题