list 根据组合
public static void main(String[] args) {
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
List<List<String>> combinations = generateCombinations(list, 3);
for (List<String> combination : combinations) {
System.out.println(combination);
}
}
public static List<List<String>> generateCombinations(List<String> list, int k) {
List<List<String>> result = new ArrayList<>();
if (k > list.size() || k <= 0) {
return result;
}
backtrack(list, k, 0, new ArrayList<>(), result);
return result;
}
private static void backtrack(List<String> nums, int k, int start, List<String> tempList, List<List<String>> result) {
if (tempList.size() == k) {
result.add(new ArrayList<>(tempList));
return;
}
for (int i = start; i < nums.size(); i++) {
tempList.add(nums.get(i));
backtrack(nums, k, i + 1, tempList, result);
tempList.remove(tempList.size() - 1);
}
}