递归输出一组元素的排列组合方式

第一种,输出N个不同元素的所有排列组合,比如{a, b, c}的排列方式有:abc, acb, bac, bca, cab, cba。
void Perm(string str, string insert = “”)
{
 if(1 == str.length())
 {
  cout << insert << str << endl;

  return;
 }
 else
 {
  for(int index = 0; index < str.length(); ++index)
  {
   Swap(str, 0, index);
   string temp = insert + str[0];
   Perm(str.substr(1, str.length() – 1), temp);
   Swap(str, 0, index);
  }
 }
}

第二种,输出N个不同元素所有排列组合的子集,比如{a, b}的所有排列方式的子集有:ab, ba, a, b。
void PermAll(string &str, string insert = “”)
{
 if(1 == str.length())
 {
  cout << insert << endl;
  cout << insert << str << endl;

  return;
 }
 else
 {
  cout << insert << endl;
  for(int index = 0; index < str.length(); ++index)
  {
   Swap(str, 0, index);
   string temp = insert + str[0];
   PermAll(str.substr(1, str.length() – 1), temp);
   Swap(str, 0, index);
  }
 }
}

上面两个函数中都引用了Swap:
void Swap(string &str, int a, int b)
{
 char temp = str[a];
 str[a]  = str[b];
 str[b]  = temp;
}

写完之后,测试应该是正确的,但总有种感觉,唉,自己又有点笨~