输出任意数目组合的字符串


package com.xianfengshangtai.interview;

/**
* 题目:给定一个字符串,里面用空格分开为6个或者更多的子单元,如,01 02 03 04 05 06 06 08...
* 请写一个程序,返回任6个进行组合的所有字符串。请保持输出字符串中的元素顺序与原始顺序已知
* 示例:
* 输入:
* 01 02 03 04 05 06 07
* 输出的字符串数组为:
* 01 02 03 04 05 06
* 01 02 03 04 05 07
* 01 02 03 04 06 07
* 01 02 03 05 06 07
* 01 02 04 05 06 07
* 01 03 04 05 06 07
* 02 03 04 05 06 07
*
*/
public class Problem23_25 {
public static void main(String[] args) {
String input = "01 02 03 04 05 06 07";
String [] target = input.split(" ");
if(target.length>=6){
distil(null,target,6);
}
}

public static void distil(String[] selected,String[] target,int count){
if(target ==null||target.length return;
}


if(count==1||target.length==count){
//if(____________________)
String selectedStr = "";
if(selected!=null){
for(int i=0,cnt=selected.length;i selectedStr += selected[i]+" ";
}
}
/**
* 如果要输出的子单元的的单元长度为1的话
* 则输出数组target里面的每个元素,每行一个元素
*/
if(count ==1){
for(int i=0,cnt=target.length;i System.out.println(selectedStr+target[i]+" ");
}
}else{
/**
* 否则,一行输出数组target里面的所有元素
*/
for(int i=0,cnt=target.length;i selectedStr +=target[i]+ " ";
}
System.out.println(selectedStr);
}
}else{
/**
* 生成新的target和selected数组
*/
String[] newSelected = null;
if(selected == null){
newSelected = new String[] {target[0]};
}else{
newSelected = new String[selected.length+1];
for(int i=0,cnt=selected.length;i newSelected[i] = selected[i];
}
newSelected[selected.length] = target[0];
}
String [] newTarget = new String[target.length-1];
for(int i=1,cnt=target.length;i newTarget[i-1] = target[i];
}
//distil(selected, newTarget, count);
distil(newSelected, newTarget, count-1);
//________________________
distil(selected, newTarget, count);
//________________________
}
}
}



运算结果:

01 02 03 04 05 06
01 02 03 04 05 07
01 02 03 04 06 07
01 02 03 05 06 07
01 02 04 05 06 07
01 03 04 05 06 07
02 03 04 05 06 07

你可能感兴趣的:(java)