码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-08-29 21:42:11      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

技术分享技术分享

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!)。


版权声明:本文为博主原创文章,未经博主允许不得转载。

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

标签:

原文地址:http://blog.csdn.net/wangfengfan1/article/details/48091679

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!