首頁  >  文章  >  Java  >  如何在 Java 中從多個清單產生所有可能的唯一組合?

如何在 Java 中從多個清單產生所有可能的唯一組合?

Patricia Arquette
Patricia Arquette原創
2024-10-26 19:57:02307瀏覽

How to Generate All Possible Unique Combinations from Multiple Lists in Java?

Java 中的多個清單組合產生器

問題:

問題:
X: [A, B, C] 
Y: [W, X, Y, Z]

給定可變數量的列表任意長度,產生一個包含所有輸入列表中所有可能的唯一元素組合的列表。例如,給定清單:
[AW, AX, AY, AZ, BW, BX, BY, BZ, CW, CX, CY, CZ]

函數應產生12 個組合:

答案:
<code class="java">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));
    }
}</code>

此問題需要遞歸方法方法:
<code class="java">List<List<Character>> lists = new ArrayList<>();
lists.add(Arrays.asList('A', 'B', 'C'));
lists.add(Arrays.asList('W', 'X', 'Y', 'Z'));

List<String> result = new ArrayList<>();
generatePermutations(lists, result, 0, "");</code>
使用此函數:

以上是如何在 Java 中從多個清單產生所有可能的唯一組合?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn