怎样输出几个数的全排列呢?(C++编程实现)

来源:互联网 发布:淘宝店的等级划分 编辑:程序博客网 时间:2024/06/07 14:51

第一种方法,比较简单,借助于STL库中的next_permutation函数。next_permutation的作用就是计算全排列。

示例:输出整数数组array的全排列


 

第二种方法,不用STL库,改用递归的思想来实现。

示例:输出字符串str中各个字符的全排列(数组与此类似,这里给出针对字符串的代码)

 

---------------

今天又看到此文,动手又实践了一下,

输出几个数的全排列:

(调用示例:vector<string> rst; testAllPermutations("", "abc", rst);

//列出全排列void testAllPermutations(const string& preStr, const string& nextArr, vector<string>& retVec){    if(nextArr.length() == 1)    {        retVec.push_back(nextArr);        return;    }    for (unsigned int i = 0; i < nextArr.length(); ++i)    {        string now(1, nextArr[i]);        string next(nextArr);        next = next.erase(i, 1);        vector<string> retVal;        testAllPermutations(now, next, retVal);        for(unsigned int j = 0; j < retVal.size(); ++j)        {            retVec.push_back(now+retVal[j]);        }    }}

在此基础上,输出几个数的所有的可能组合:

//列出所有可能的组合void testAllCombination(const string& preStr, const string& nextArr, vector<string>& retVec){    if(preStr.length() == 0)    {        //初始时将单字符组合形式记录下来        for (unsigned int t = 0; t < nextArr.length(); ++t)        {            retVec.push_back(string(1, nextArr[t]));        }    }    if(nextArr.length() == 1)    {        retVec.push_back(nextArr);        retVec.push_back("");        return;    }    for (unsigned int i = 0; i < nextArr.length(); ++i)    {        string now(1, nextArr[i]);        string next(nextArr);        next = next.erase(i, 1);        vector<string> retVal;        testAllCombination("", next, retVal); //首参数传空        for(unsigned int j = 0; j < retVal.size(); ++j)        {            retVec.push_back(now+retVal[j]);        }    }}
不过,这样最后计算的结果,数据会有一定重复,过滤一下就OK。



原创粉丝点击