您的位置:首页 > Web前端

剑指Offer—字符串排列

2016-05-12 20:20 274 查看
题目描述:输入一个字符串,打印出该字符串中字符的所有排列。

解析:step 1:求所有可能出现第一个位置的字符。把第一个字符与后面的每个字符交换。

step 2:固定第一个字符,将后面的字符利用递归进行全排列。

#include <iostream>
#include <stdio.h>
using namespace std;
void StringPermutation(char *pStr,char *pBegin);

//字符串排列
void Permutation(char *pStr)
{
if(pStr==NULL)
return;
StringPermutation(pStr,pStr);
}

void StringPermutation(char *pStr,char *pBegin)
{

if(*pBegin=='\0')
printf("%s\n",pStr);
else
{
for(char* pCh=pBegin;*pCh!='\0';++pCh)
{
//将第一个字符与后面的字符依次置换
char tem=*pCh;
*pCh=*pBegin;
*pBegin=tem;
//递归遍历后面的字符

StringPermutation(pStr,pBegin+1);
//递归完成后,将调换的字符还原。
tem=*pBegin;
*pBegin=*pCh;
*pCh=tem;
}
}
}
//测试代码
void Test(char *pStr)
{
if(pStr==NULL)
printf("Test for NULL begins:\n");
else
printf("Test for %s begins:\n",pStr);

Permutation(pStr);
printf("\n");
}
int main()
{
//cout << "Hello world!" << endl;
char s1[]=" ";
Test(s1);

char s2[]="a";
Test(s2);

char s3[]="abc";
Test(s3);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: