1.m个字母的全排列
package cn.rainbow.algorithm;
import com.github.sd4324530.fastweixin.util.JSONUtil;
import org.apache.commons.lang.StringUtils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class FullArray {
public static void main(String[] args){
List<String> result =new ArrayList<>();
Set<String> s = new HashSet<String>();
s.add("jia");
s.add("home");
s.add("plus");
s.add("super");
String[] arr = s.toArray(new String[s.size()]);
for(int k=1;k<s.size()+1;k++){
int n=k;//取n个数
List<String> list=new ArrayList<String>();
for(int i=0;i<n;i++)
list.add("");//存入-1/""的目的是初始化数组长度为n,并且使其值不是需要的对象(数字或字符)
sort(list,arr,n,result);
}
System.out.println(JSONUtil.toJson(result));
}
public static void sort(List<String> list,String[] arr,int n,List<String> result){
if(n==0){
result.add(StringUtils.join(list,","));
return;//重点,不能漏
}
for(int i=0;i<arr.length;i++){
if(!list.contains(arr[i]))//查找list里有无此值
list.set(list.size()-n,arr[i]);//如果没有则存入list
else
continue;
sort(list,arr,n-1,result);//如果存入了一个对象,就继续递归
list.set(list.size()-n,"");//回溯时把list重置为-1/空字符
}
}
}
/**
* 运行结果
*/
[
"super",
"jia",
"plus",
"home",
"super,jia",
"super,plus",
"super,home",
"jia,super",
"jia,plus",
"jia,home",
"plus,super",
"plus,jia",
"plus,home",
"home,super",
"home,jia",
"home,plus",
"super,jia,plus",
"super,jia,home",
"super,plus,jia",
"super,plus,home",
"super,home,jia",
"super,home,plus",
"jia,super,plus",
"jia,super,home",
"jia,plus,super",
"jia,plus,home",
"jia,home,super",
"jia,home,plus",
"plus,super,jia",
"plus,super,home",
"plus,jia,super",
"plus,jia,home",
"plus,home,super",
"plus,home,jia",
"home,super,jia",
"home,super,plus",
"home,jia,super",
"home,jia,plus",
"home,plus,super",
"home,plus,jia"
]
文章来源地址https://www.toymoban.com/news/detail-593755.html
文章来源:https://www.toymoban.com/news/detail-593755.html
到了这里,关于算法--排列组合的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!