您的位置:首页 > 职场人生

面试题28:求字符的全排列

2015-06-01 17:48 477 查看
输入一字符串(要求不存在重复字符),打印出该字符串中字符中字符的所有排列。

例如:输入"abc",输出结果为abc, acb, bac, bca, cab和cba。

算法思路:以abc为例,首先固定a,a之后还有bc,对bc进行全排列,对bc进行全排列可以再把b固定对c进行全排列,只剩一个c时已经到了字符结尾,所以输出当前的序列为abc,然后返回上一步,上一步中是abc,交换bc位置变为acb,然后对cb进行全排列,将c固定对b全排列,输出acb,输出之后返回上一步,再将cb交换回来变为bc,此时整体的第一次循环结束,开始下一次循环,下一次循环将b和a交换位置,重复上述步骤,结束后将b和a换回ab,再将c和a换位置,再重复上述步骤,直到字符串中所有的字符在第一个位置固定过之后,函数结束,全排列输出完毕。

#include <iostream>
using namespace std;
void Permutation(char * str,char * begin);
void Permutation(char * str)
{
if(str==NULL)
return;
Permutation(str,str);

}

void Permutation(char * str,char * begin)
{
if(*begin=='\0')
{
//输出当前的排列
cout<<str<<endl;
}
else
{
for(char * ch=begin;*ch!='\0';++ch)
{
//begin指向第一个字符,ch用来遍历字符串,并和begin交换数值,使每个字符都可以固定在第一个位置
char temp=*ch;
*ch=*begin;
*begin=temp;
//确定第一个字符之后,对第一个字符之后的字符进行递归,查找全排列
Permutation(str,begin+1);
//换过去后再还原
temp=*ch;
*ch=*begin;
*begin=temp;
}
}
}

int main()
{
char str[]="abc";
Permutation(str);
return 0;
}


java:

public class AllPailie {

/**
* 输出字符串的全排列并去掉重复的元素
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
pailie("aac");
}

public static void pailie(String str)
{
char[] ch=str.toCharArray();
HashSet<String> set=new HashSet<String>();
allPailie(ch,0,set);
Iterator it=set.iterator();
while(it.hasNext())
{
String s=(String) it.next();
System.out.println(s);
}
}

public static void allPailie(char[] ch,int begin,HashSet<String> set)
{
if(begin==ch.length)
{
set.add(new String(ch));
}
else
{
for(int i=begin;i<ch.length;i++)
{
char temp=ch[i];
ch[i]=ch[begin];
ch[begin]=temp;
allPailie(ch,begin+1,set);
temp=ch[i];
ch[i]=ch[begin];
ch[begin]=temp;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: