You are given a list of sets of numbers (nested) to derive a sequence such that :
- Exactly 1 number must be selected from each of the sets
- The sequence is arranged in the ascending order of the sum of these numbers
- No 2 terms of the sequence can be the same (must not repeat)
All the numbers are positive and they are unique within each set Need the most efficient way to get the nth term of the sequence
Consider the following example:
Given:
[[1, 2, 5] ,
[12, 15, 19, 30, 54],
[55, 90, 97, 23, 54]]
Sequence (Output):
[1, 12, 23] (sum = 36 (min possible))
[2, 12, 23] (sum = 37)
[1, 15, 23] (sum = 39)
[2, 15, 23] (sum = 40)
[5, 12, 23] (sum = 40)
[1, 19, 23] (sum = 43)
[5, 15, 23] (sum = 43)
and so on...
My current approach is brute forcing (getting the product of the sets) and then sorting them, but obviously it is not O(polynomial). Is there a more efficient approach to this?
(edit): Note that the output is ordered and the different sets may have same numbers (see the 54 is common in the above example)
Turns out it is a np-complete problem. A specific case for 2 sets of equal length is a famous problem called X+Y problem
https://en.wikipedia.org/wiki/X_%2B_Y_sorting
Also a similar problem has been answered here https://cs.stackexchange.com/questions/46910/efficiently-finding-k-smallest-elements-of-cartesian-product
It seems that the best way to solve it is to use breadth first search. Currently it cannot be solved in polynomial time and theorectically it may be possible to solve it with complexity O(n^m) where m is the no. of sets and n is the max length of the set. Currently this remains an open problem in computer science and mathematics.