参数的排列组合2
参数的取值范围是:[“a”,”b”,”c”,”d”],求其所有的排列组合
先给出答案:
共15个,分别是:
abc, d, abd, b, c, a, ac, ad, bcd, ab, bc, acd, abcd, bd, cd
单元测试:
@Test
public void test_factorialaa(){
String base[]=new String[]{"a","b","c","d"};
Set<String>result=AssembleUtil.assemble( base, 0, base.length,true);
System.out.println(result.size());
System.out.println(result);
}
核心代码:
package com.common.util;
import com.string.widget.util.ValueWidget;
import java.util.HashSet;
import java.util.Set;
/**
* Created by huangweii on 2016/1/23.
*/
public class AssembleUtil {
/***
*
* @param base :[a,b,c,d]
* @param times
* @param remaining : 剩余要选择的个数
* @return
*/
public static void assemble(Set<String> result, StringBuffer buffer, String base[], int times, int remaining, boolean isSort){
if(remaining<=1){
buffer.append(base[base.length-1]);
addElementBySort(result, buffer, isSort);
}else{
for(int i=0;i<remaining;i++){
StringBuffer bufferTmp=new StringBuffer(buffer);
bufferTmp.append(base[base.length-1-i]);
addElementBySort(result, bufferTmp, isSort);
assemble(result,bufferTmp, SystemHWUtil.aheadElement(base,base.length-1-i), times, remaining-1,isSort);
}
}
}
/***
*
* @param base
* @param times
* @param remaining : 剩余要选择的个数
* @param isSort : 是否对"acb"进行排序,<br />排序结果:"abc"
* @return
*/
public static Set<String> assemble( String base[], int times, int remaining, boolean isSort){
Set<String>result=new HashSet<String>();
StringBuffer buffer=new StringBuffer();
AssembleUtil.assemble(result,new StringBuffer(), base, 0, base.length,true);
return result;
}
public static void addElementBySort(Set<String> result, StringBuffer buffer, boolean isSort) {
String str=buffer.toString();
if(isSort){
str= ValueWidget. sortStr(str);
}
result.add(str);
}
/***
* 参数的取值个数,ab和ba算一种
* @param argCount
* @return
*/
public static int getAssembleSum(int argCount){
int sum=0;
for(int i=0;i<argCount;i++){
int count=i+1;//参数组合的个数
sum+=(SystemHWUtil. factorial(argCount,count)/SystemHWUtil.arrayArrange(count));
}
return sum;
}
}