数学基础:二、组合算法(递归)
组合算法也是使用递归算法产生组合结果
public class Lesson8_1 {
/**
* @Description 组合算法
* @param has 已经选中要组合的数据
* @param rest 剩余未(待)组合的数据
* @param n 要选出的个数
* @param resultList 组合结果
*/
public static void combine(List<String> has, List<String> rest, int n, List<List<String>> resultList) {
// 已达到选中的数量,直接添加到结果集中
if (has.size() == n) {
resultList.add(has);
} else {
int size = rest.size();
for (int i = 0; i < size; i++) {
// 为了不破坏递归前的原数据,设置临时变量tmpHas和tmpRest来保存中间值
List<String> tmpHas = new ArrayList<>(has);
// 从遍历的待组合数据中,取出一条数据作为组合的一个值
tmpHas.add(rest.get(i));
// 新的待组合结果只从选中后的数据中找,往前找只会和之前a, b或b, a这种重复
List<String> tmpRest = new ArrayList<>(rest.subList(i + 1, size));
// 递归调用,剩余待组合数据继续生成组合值
combine(tmpHas, tmpRest, n, resultList);
}
}
}
public static void main(String[] args) {
String[] arr = {"1", "2", "3", "4", "5"};
List<String> restList = Arrays.asList(arr);
List<List<String>> resultList = new ArrayList<>();
combine(new ArrayList<>(), restList, 3, resultList);
System.out.println(resultList);
}
}