Home > Java > javaTutorial > body text

How can I generate all possible combinations from multiple lists of unknown length using recursion in Java?

DDD
Release: 2024-11-04 09:45:30
Original
420 people have browsed it

How can I generate all possible combinations from multiple lists of unknown length using recursion in Java?

Iterative Generation of All Combinations from Multiple Lists using Recursion in Java

Envisage a scenario where you're confronted with an assortment of lists, each possessing an undisclosed length. Your task is to produce a singular list that incorporates all unique combination possibilities. To illustrate, consider the following lists:

X: [A, B, C] 
Y: [W, X, Y, Z]
Copy after login

From these lists, you should be able to generate 12 combinations:

[AW, AX, AY, AZ, BW, BX, BY, BZ, CW, CX, CY, CZ]
Copy after login

If an additional third list of 3 elements were introduced, the total number of combinations would expand to 36.

To achieve this complex combination generation, recursion emerges as a powerful tool:

<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>
Copy after login

In this meticulously crafted recursive algorithm, the parameter lists represents the collection of input lists, characterized by an indeterminate quantity and length. The result list stands in as the repository of all permutations generated during the process. The parameters depth and current facilitate the traversal of the input lists and the construction of individual combinations, respectively.

The ultimate invocation of this generative function orchestrates the entire process:

<code class="java">generatePermutations(lists, result, 0, "");</code>
Copy after login

Through the harmonious collaboration of recursion and the Java Collection Framework, this algorithm empowers you to effortlessly produce every conceivable combination from an arbitrarily large ensemble of lists.

The above is the detailed content of How can I generate all possible combinations from multiple lists of unknown length using recursion in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template