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

本文介绍了一种使用递归实现的不同元素排列组合算法及其子集的生成方法,并提供了具体的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一种,输出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;
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值