题目见:
http://community.csdn.net/Expert/TopicView3.asp?id=5126306
用C++写一个函数, 如 Foo(const char *str), 打印出 str 的全排列,
如 abc 的全排列: abc, acb, bca, dac, cab, cba
解答:
呵呵,来给大伙说说原理:
A(n,n) = n!
=>A(n,n) = A(n-1,n-1)*n
有了递推公式,就可以写递归函数了:
#include
<
vector
>
#include
<
string
>
#include
<
iostream
>
#include
<
algorithm
>
#include
<
iterator
>
using
namespace
std;

typedef vector
<
string
>
Permutation;
typedef vector
<
string
>
::iterator PmtIterator;

//
计算templet字符串中从pos位置开始的全排列
Permutation permute(
const
string
&
templet,
string
::size_type pos)

...
{
Permutation temp;
if (pos == templet.size()-1)

...{
temp.push_back(string(1, templet[templet.size()-1]));
}
else

...{
// 计算从pos+1开始的全排列sub
// 然后就sub的每一项,计算出pos位置开始的全排列
Permutation sub = permute(templet, pos+1);
for (PmtIterator iter = sub.begin(); iter != sub.end(); ++iter)

...{
for (string::size_type pos1 = 0; pos1 <= iter->size(); ++pos1)

...{
temp.push_back(*iter);
temp[temp.size()-1].insert(pos1, 1, templet[pos]);
}
}
}
return temp;
}

int
main(
void
)

...
{
string templet = "abc";
Permutation pmt = permute(templet, 0);
copy(pmt.begin(), pmt.end(), ostream_iterator<string>(cout, " "));
cout << endl;
return 0;
}