编写一个方法,确定某字符串的所有排列组合

来源:互联网 发布:2am 2pm 知乎 编辑:程序博客网 时间:2024/04/20 02:37

public static ArrayList<String> getPerms(String str)
{
if(str==null)
return null;
ArrayList<String> permutations=new ArrayList<String>();
if(str.length()==0)//终止条件
{
permutations.add("");
return permutations;
}
char first=str.charAt(0);//取得第一个字符
String remainder=str.substring(1);//移除第一个字符
ArrayList<String> words=getPerms(remainder);
for(String word:words)
{
for(int j=0;j<=word.length();j++)
{
String s=insertCharAt(word,first,j);
permutations.add(s);
}
}
return permutations;
}
public static String insertCharAt(String word,char c,int i)
{
String start=word.substring(0,i);
String end=word.substring(i);
return start+c+end;
}

由于将会有N!种排列组合,这种解法的时间复杂度为O(n!)。


0 0
原创粉丝点击