Print all combinations of phrases that can be formed by picking words from each of the given lists

Given N lists of words, print all combinations of phrases that can be formed by picking one word each from each of the given lists.


For example,


list 1 -> [ John, Emma, Chloe ]
list 2 -> [ Plays, Hates, Watches ]
list 3 -> [ Cricket, Soccer, Chess ]


John Plays Cricket
John Plays Soccer
John Plays Chess
John Hates Cricket
John Hates Soccer
John Hates Chess
John Watches Cricket
John Watches Soccer
John Watches Chess
Emma Plays Cricket
Emma Plays Soccer
Emma Plays Chess
Emma Hates Cricket
Emma Hates Soccer
Emma Hates Chess
Emma Watches Cricket
Emma Watches Soccer
Emma Watches Chess
Chloe Plays Cricket
Chloe Plays Soccer
Chloe Plays Chess
Chloe Hates Cricket
Chloe Hates Soccer
Chloe Hates Chess
Chloe Watches Cricket
Chloe Watches Soccer
Chloe Watches Chess

The idea is to use recursion. At each point in the recursion, we consider each word in current list and append the word to output one by one, recurse for next list. Finally, when no list is left to recurse (i.e. all lists are considered), we print the output phase.

Below is C++ and Java implementation of the idea –


Download   Run Code


Download   Run Code

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Get great deals at Amazon

Leave a Reply

newest oldest most voted
Notify of

Looks like recursion was fatal to Chloe 😉