Advertisement
hoangreal

Generate all possible combinations of the list of lists

Oct 21st, 2024
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.26 KB | None | 0 0
  1. """
  2. Given k lists: list A, list B, list C, ... list K, generate all possible combinations of the list using all values of the list.
  3. """
  4.  
  5. def solve(lists: list[list]):
  6.     """
  7.    Time Complexity: O(m^n)
  8.    Space Complexity: O(n * m^n)
  9.  
  10.    Where n is the number of input lists and m is the average length of each list.
  11.    """
  12.    
  13.     # Handle the edge case where no lists are provided.
  14.     if not lists:
  15.         return [[]]  # Return a list with an empty combination.
  16.  
  17.     # If any list is empty, there can be no combinations.
  18.     for lst in lists:
  19.         if not lst:
  20.             return []
  21.  
  22.     result = []
  23.  
  24.     def backtrack(index, current_combination):
  25.         # If we've reached the end, add the current combination to the results.
  26.         if index == len(lists):
  27.             result.append(current_combination.copy())
  28.             return
  29.         # Iterate over each element in the current list.
  30.         for element in lists[index]:
  31.             current_combination.append(element)  # Choose an element.
  32.             backtrack(index + 1, current_combination)  # Move to the next list.
  33.             current_combination.pop()  # Backtrack to try the next element.
  34.  
  35.     backtrack(0, [])
  36.     return result
  37.  
  38. lsts = [[1, 2], [3], [4, 5, 6]]
  39. print(solve(lsts))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement