首頁 > Java > java教程 > 主體

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

Patricia Arquette
發布: 2024-10-26 19:57:02
原創
307 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!