具体方法代码如下:
输出字符串str中各个字符的全排列(数组与此类似,这里给出针对字符串的代码)
[cpp] view plaincopy
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int array[] = {1, 2, 3, 4};
const int iArraySize = sizeof(array)/sizeof(int);
//删除str的第n个字符
void DeleteCharAt(string& str, int n)
{
if (n < 0 || n >= str.length())
{
return;
}
string tmpStr(str.substr(n + 1));
str = str.substr(0, n) + tmpStr;
}
//base 以该字符串作为基础字符串,进行选择性组合。
//buff 所求字符串的临时结果
//result 存放所求结果
void ListAll(string& strBase, string strBuff, vector<string>& result)
{
if (strBase.length() <= 0)
{
result.push_back(strBuff);
}
for(int i = 0; i < strBase.length(); i++)
{
string tmp(strBase);
DeleteCharAt(tmp, i);
ListAll(tmp, strBuff + strBase[i], result);
}
}
int main(){
int iCnt = 0;
string str = "1324";
vector<string> vResult;
ListAll(str, "", vResult);
//Output the result
for (int i = 0; i < vResult.size(); ++i)
{
cout << vResult[i] << " ";
}
cout << "/n";
cout << "Total number: " << vResult.size() << endl;
return 0;
温馨提示:内容为网友见解,仅供参考