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]
From these lists, you should be able to generate 12 combinations:
[AW, AX, AY, AZ, BW, BX, BY, BZ, CW, CX, CY, CZ]
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>
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>
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!