字符串的全排列。

输入一个字符串,其含有的字符不同。程序输出该字符串的所有全排列。

1.用递归调用实现:代码如下

#include<iostream>
using namespace std;
void swap(int &x,int &y)  //交换函数
{
 int t;
 t = x;
 x = y;
 y = t;
}
void AllPermutation(char *perm, int left, int right)  //全排列
{
 if (right < 0)
  return ;
 int i = 0;
 if (left == right)
 {
  for (i = 0; i <= right; i++)
  {
   cout << perm[i];
  }
  cout << endl;
 }
 else
 {
  for (i = left; i <= right; i++)
  {
   swap(perm[i], perm[left]);//交换
   AllPermutation(perm, left + 1, right);//递归
   swap(perm[i], perm[left]);//还原
  }
 }
}
int main()
{
 char s[] = "abc";
 AllPermutation(s,0,2);
 return 0;
}


2.另一种写法:

#include<iostream>
#include<assert.h>
using namespace std;
void swap(int &x,int &y)
{
 int t;
 t = x;
 x = y;
 y = t;
}

void Permutation(char* pStr, char* pBegin)
{
 assert(pStr!=NULL && pBegin!=NULL);
 if (*pBegin == '\0')
  printf("%s\n", pStr);
 else
 {
  for (char* pCh = pBegin; *pCh!= '\0'; pCh++)
  {
   swap(*pBegin, *pCh);
   Permutation(pStr, pBegin + 1);
   swap(*pBegin, *pCh);
  }
 }
}
int main()
{
 char s[] = "abc";
 //AllPermutation(s,0,2);
 Permutation(s, s);
 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值