打印出一个字符串的全排列(重复的只计算一次)

本文介绍了一种计算字符串全排列的方法,特别关注如何去除重复排列。通过先对字符串进行排序并利用循环递归思想,该算法能有效生成所有不重复的全排列组合。

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

给定hello则它的全排列共有 5*4*3*2*1/ (2*1)=60种。

思想(先不考虑去重复):
首先取第一个字符如h,然后计算剩下4个字符ello的全排列,然后再将h和这些全排列相加就OK了,然后再取第二个... 第三个...,典型的循环+递归思想。
如果要去重,可以考虑先将整个字符串排序,hello -> ehllo,在循环的时候,首先判断当前字符和前一个字符是否相同,如果相同则说明这个字符已经处理,跳过即可。

java code:

@Test
public void run()
{
String str = "hello";
char[] array = str.toCharArray();
Arrays.sort(array);
List<String> result = this.compose(array);
System.out.println(result.size());
for (String s : result)
{
System.out.println(s);
}
}

private List<String> compose(char[] array)
{
List<String> result = new LinkedList<String>();
if (array.length == 1)
{
result.add(String.valueOf(array[0]));
return result;
}
for (int i = 0; i < array.length; i++)
{
char ch = array[i];
//if the current character is the same with previous one, it means this character has been arranged, skip it
if (i > 0 && ch == array[i - 1])
{
continue;
}
List<String> subList = this.compose(this.getSubarray(array, i));
for (String str : subList)
{
result.add(String.valueOf(ch) + str);
}
}
return result;
}

private char[] getSubarray(char[] array, int exclude)
{
char[] sub = new char[array.length - 1];
System.arraycopy(array, 0, sub, 0, exclude);
System.arraycopy(array, exclude + 1, sub, exclude, array.length - exclude - 1);
return sub;
}


复杂度: N!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值