I'm working on this algorithm exercice from GeeksForGeeks:
Given a list of arrays (of any size, not limited to two arrays), find all combinations where each combination contains one element from each given array.
Examples:
Input:
[[1, 2], [3, 4]]
Output:
1 3 1 4 2 3 2 4
I tried to resolve it myself using this approach:
Initialize "result" list of arraylist.
For each element of the first array in the input list:
depth = 1
while(depth < list.size())
arrayToCombineWithItsElmt = list.get(depth)
for(int i = 0; i < arrayToCombineWithItsElmt.size(); i++)
GenerateCombinations(result, arrayToCombineWithItsElmt(i))
depth++
return result
generateCombinations(List<ArrayList> result, int element)
method should:
- copy result list (which contains previous combinations)
- remove all elements of result list
- iterate over the copied list and for each Array add the element
- Add the array to result list.
I didn't code (using Java) it as I felt that it's not correct (very complex way to solve). From this brute force algorithm that I got after trying to resolve an example manually, how to optimize?