Fundamentals/Backtracking Template
← PrevNext →
Given a non-negative integer n, generate every n-letter word formed from the letters 'a' and 'b' in lexicographical order. The function dfs performs a depth-first traversal of the state-space tree, appending each completed word to res.
Input
n: target word length
res: list to populate with completed words
startIndex: current depth in the recursion (start with 0)
path: working buffer of letters chosen so far
Output
Nothing is returned; res is mutated in place to hold all 2^n words in lexicographical order.
Examples
Example 1
Inputn = 2, res = [], startIndex = 0, path = []
Result: res = ["aa", "ab", "ba", "bb"]
Example 2
Inputn = 4, res = [], startIndex = 0, path = []
Result: res = ["aaaa", "aaab", ..., "bbbb"] (16 entries)
Constraints
0 <= n <= 12
Only the letters 'a' and 'b' may appear in each word.