java递归实现一个字符串的全排列并去掉重复的排列
算法:递归实现
代码如下:
package com.ibianma.zifuchuan;
import java.lang.String;
public class FullPermutation {
private static void exChange(char[] chars,int i,int j){
char temp = chars[i];
chars[i]=chars[j];
chars[j]=temp;
}
private static void permitation(char[] chars,int start){
if (chars==null||start<0)
return;
if (start==chars.length){
System.out.println(chars);
}
else {
for (int i = start; i <chars.length ; i++) {
if (!isDuplicate(chars,start,i))
continue;
exChange(chars,start,i);
permitation(chars,start+1);
exChange(chars,start,i);
}
}
}
private static boolean isDuplicate(char[] str,int begin,int end ){
for (int i = begin; i <end ; i++) {
if (str[i]==str[end])
return false;
}
return true;
}
public static void permitation(String str){
char[] chars = str.toCharArray();
permitation(chars,0);
}
public static void main(String[] args) {
String str = new String("abcc");
permitation(str);
}
}
结果如下:
abcc
acbc
accb
bacc
bcac
bcca
cbac
cbca
cabc
cacb
ccab
ccba