Intuition
Build out the combinations recursively and append them to the result. May be tempting to use for loops but the code is more complicated for no real gain…just keep it simple.
Implementation
Visual
Review 1
The iterative solution is probably more intuitive:
Implementation (iterative)
Note on the time complexity: Each digit can have at most 4 possibilities therefore the complexity is o(4**n) where n is the number of digits. Think in bits!
Review 2
This is actually a pretty fascinating problem because we have a choice: pure recursion or backtracking. Backtracking is actually the less efficient of the two because we must recurse search the same branch for every letter in every index i (we can get around this but it bloats the code because generally speaking backtracking relies on the state array at the leaf node rather than building results from the top down)! Of course with these constraints there is no difference at all but Its worth understanding the different approaches here:
Implementation (recursion)
I will implement back tracking properly here…this is the same as the first implementation but without the state propagation through the call stack.
Implementation (backtracking)
This is of course a small nuance but it would make a huge difference under tighter constraints.