Recursively print all sentences that can be formed from list of word lists
Pattern: Recursion trees
There is one list of words per position in the sentence. Recurse over the lists, choosing each word of the current list in turn, and join the choices when every list has given one word.
The problem
You are given several lists of words. Form every sentence that takes exactly one word from each list, keeping the lists
in their order, and return the sentences with single spaces between words. For example, [you, we], [have, are] and
[sleep, eat, drink] give 12 sentences, starting you have sleep, you have eat, you have drink, you are sleep.
The link above is a GeeksforGeeks article. The function name sentences and this exact order (the first list changes
slowest) are this guide's own.
Think first
- How many sentences are there?
- At each step, what choice do you make?
- In which order do the sentences come out?
Hints
Brute force, and why it fails
This is the whole job: every sentence must be produced. Nested loops work only when the number of lists is fixed; recursion handles any number.
The key insight
A recursion of depth k is a set of k nested loops whose number is decided at run time.
Dry run
The lists are [you, we], [have, are] and [sleep, eat, drink].
The plan
function build(i, picked):
if i == number of lists: record picked joined by " "; return
for w in lists[i]:
add w; build(i + 1, picked); remove w
build(0, [])
Complexity
- Time
O(product of sizes × k)- Space
O(k)
Each of the sentences is k words long, and the recursion is k deep.
Edge cases
- One list: each word is a sentence.
- Lists of one word: exactly one sentence.
- Many lists: the count grows quickly.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<String> sentences(String[][] words) {
List<String> out = new ArrayList<>();
build(words, 0, new ArrayList<>(), out);
return out;
}
private void build(String[][] words, int i, List<String> picked, List<String> out) {
if (i == words.length) { out.add(String.join(" ", picked)); return; } // one word chosen from every list
for (String w : words[i]) { // try each word of list i in turn
picked.add(w);
build(words, i + 1, picked, out);
picked.remove(picked.size() - 1);
}
}
}C++
class Solution {
public:
vector<string> sentences(vector<vector<string>>& words) {
vector<string> out, picked;
build(words, 0, picked, out);
return out;
}
void build(vector<vector<string>>& words, size_t i, vector<string>& picked, vector<string>& out) {
if (i == words.size()) { // one word chosen from every list
string s;
for (size_t k = 0; k < picked.size(); k++) s += (k ? " " : "") + picked[k];
out.push_back(s);
return;
}
for (const string& w : words[i]) { // try each word of list i in turn
picked.push_back(w);
build(words, i + 1, picked, out);
picked.pop_back();
}
}
};Python
class Solution:
def sentences(self, words: list[list[str]]) -> list[str]:
out = []
def build(i: int, picked: list) -> None:
if i == len(words):
out.append(" ".join(picked)) # one word chosen from every list
return
for w in words[i]: # try each word of list i in turn
picked.append(w)
build(i + 1, picked)
picked.pop()
build(0, [])
return outCommon mistakes
- Hard-coding three nested loops.
- Adding a space after the last word.
- Changing the list order.