Problem
Given a list of lists containing elements, write a function that prints out the permutations of of the elements such that, each of the permutation set contains only 1 element from each list and there are no duplicates in the list of permutation sets.
Examples
Example 1:
|
|
Solution
Method 1 - Backtracking
This is a combination problem and we can solve it using backtracking (and dfs).
Read more: Permutation vs Combination. We can start from 0th list in the lists
, in listCombinations
method.
In the helper method iterates through each element in the current list (indexed by depth
), adds it to the current combination, and recursively calls itself to fill the next position.
So, for each string in first list we do recurse to all other lists to find the combinations. We add the current combination
to the result ans
whenever we reach the last list i.e. depth = n
and output contains one elements from each of the n
lists. Below is the implementation of this idea.
The method then backtracks by removing the last added element, allowing for the next element to be considered.
This implementation does not check for duplicates in the lists or results, as the generated combinations will inherently be unique given the constraints of the problem (selecting one element from each list).
Code
|
|
|
|
|
|