根据输入字符串,输出所有字符能组成的串(面试题)

比如输入"abc",得到abc, acb, bac, bca, cab, cba。

代码如下: 

#include 
#include 

using namespace std;

void func(vector &chList, vector &travelList)
{
    for (size_t i = 0; i < chList.size(); i++)
    {
        vector _travelList;
        vector _leftList;

        _travelList = travelList;
        _travelList.push_back(chList[i]);
        for (size_t j = 0; j < chList.size(); j++)
        {
            if (i != j)
            {
                _leftList.push_back(chList[j]);
            }
        }
        if (_leftList.size() == 0)//没有剩余字符
        {
            for (size_t j = 0; j < _travelList.size(); j++)
            {
                printf("%c", _travelList[j]);
            }
            printf(" ");
        }
        else
        {
            func(_leftList, _travelList);
        }
        if (travelList.size() == 0)
        {
            printf("\n");
        }
    }
}

int main(int argc, char **argv)
{
    vector chList;
    vector travelList;

    chList.push_back('a');
    chList.push_back('b');
    chList.push_back('c');
    chList.push_back('d');
    func(chList, travelList);
    getchar();
    return 0;
}

 

你可能感兴趣的:(C/C++)