给定hello则它的全排列共有 5*4*3*2*1/ (2*1)=60种。
思想(先不考虑去重复):
首先取第一个字符如h,然后计算剩下4个字符ello的全排列,然后再将h和这些全排列相加就OK了,然后再取第二个... 第三个...,典型的循环+递归思想。
如果要去重,可以考虑先将整个字符串排序,hello -> ehllo,在循环的时候,首先判断当前字符和前一个字符是否相同,如果相同则说明这个字符已经处理,跳过即可。
java code:
复杂度: N!
思想(先不考虑去重复):
首先取第一个字符如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!