题目:输入[1,2,3],输出所有可能的组形式
[[],[1], [1,2], [1,2,3], [1,3], [2], [2,3], [3] ]
package com.mjp.ai.dfs;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Objects;
/**
* Author:m
* Date: 2023/04/07 22:04
*/
public class List123 {
public static void main(String[] args) {
int[] array = new int[]{
1,2,3};
List<List<Integer>> result = dfs(array);
System.out.println(result);
}
private static List<List<Integer>> dfs(int[] array) {
if (Objects.isNull(array)) {
return Lists.newArrayList();
}
List<List<Integer>> result = Lists.newArrayList();
if (array.length == 1) {
result.add(Lists.newArrayList(array[0]));
return result;
}
List<Integer> tempList = Lists.newArrayList();
int initIndex = 0;
recursion(result, tempList, array, initIndex);
return result;
}
private static void recursion(List<List<Integer>> result, List<Integer> tempList, int[] array, int initIndex) {
// 1.终止条件
// 2.将容器添加至大容器
result.add(Lists.newArrayList(tempList));
// 3.递归
for (int i = initIndex; i < array.length; i++) {
//3.1将元素添加至小容器
tempList.add(array[i]);
//3.2递归(i+1)
recursion(result, tempList, array, i + 1);
//3.3回溯(将小容器最后一个元素去掉)
tempList.remove(tempList.size() - 1);
}
}
}