n个集合每个集合m个元素按顺序排列组合n个结果的算法
之前遇到了一个需求,一个答题,每个题目有多个选项,列出有多少种组合,然后在后台对应每种组合的推荐的结果
下面放源代码,用到了@Test注解换成主函数也一样
public class nubTest {
private static String arr[] = {"A","B","C","D","E","F","G","H"};
private static String arr1[] = {"I","J","K","L"};
private static String arr2[] = {"M","N"};
@Test
public void nuTest(){
List<String> list = new ArrayList<>();
String arrAll[][] = {arr,arr1,arr2};
nuList(0,arrAll, arrAll[0],"",list);
System.out.println(list);
}
private void nuList(int a,String arrAll[][],String arr[],String result,List<String> list){
for (int i=0; i < arrAll.length; i++) {
if(i == a) {
for (String st : arr) {
st = result + st;
if (i < arrAll.length - 1) {
nuList(i + 1, arrAll, arrAll[i + 1], st, list);
} else if (i == arrAll.length - 1) {
list.add(st);
}
}
}
}
}
}
如有错误请各位大牛指出