从多个列表生成所有组合 [英] Generate all combinations from multiple lists
问题描述
给定数量未知的列表,每个列表的长度未知,我需要生成一个包含所有可能的唯一组合的单数列表.例如,给定以下列表:
Given an unknown amount of lists, each with an unknown length, I need to generate a singular list with all possible unique combinations. For example, given the following lists:
X: [A, B, C]
Y: [W, X, Y, Z]
那么我应该可以生成 12 个组合:
Then I should be able to generate 12 combinations:
[AW, AX, AY, AZ, BW, BX, BY, BZ, CW, CX, CY, CZ]
如果添加了包含 3 个元素的第三个列表,我将有 36 种组合,依此类推.
If a third list of 3 elements were added, I'd have 36 combinations, and so forth.
关于如何在 Java 中执行此操作的任何想法?
(伪代码也可以)
Any ideas on how I can do this in Java?
(pseudo code would be fine too)
推荐答案
你需要递归:
假设您的所有列表都在 lists
中,它是一个列表列表.让 result
成为您所需排列的列表.你可以这样实现:
Let's say all your lists are in lists
, which is a list of lists. Let result
be the list of your required permutations. You could implement it like this:
void generatePermutations(List<List<Character>> lists, List<String> result, int depth, String current) {
if (depth == lists.size()) {
result.add(current);
return;
}
for (int i = 0; i < lists.get(depth).size(); i++) {
generatePermutations(lists, result, depth + 1, current + lists.get(depth).get(i));
}
}
最终调用将是这样的:
generatePermutations(lists, result, 0, "");
这篇关于从多个列表生成所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!