In trying to solve the following problem:
Generate all combinations of an array of string. Ex: Input: ['A', 'T', 'C', 'K'] Output: [ 'ATCK', 'ATC', 'ATK', 'AT', 'ACK', 'AC', 'AK', 'A', 'TCK', 'TC', 'TK', 'T', 'CK', 'C', 'K', '' ] I have the following code:
function getSpellableWords(arr) { const res = []; // helper(arr, res, 0, ''); helper(arr, res, 0, []); return res; } function helper(arr, res, i, slate) { const char = arr[i]; console.log(i, 'i') if(i === arr.length) { res.push(slate.join('')); return; } // slate = slate + char; slate.push(char) console.log(slate, 'slate') helper(arr, res, i+1, slate); slate.pop() helper(arr, res, i+1, slate); } getSpellableWords(['A', 'T', 'C', 'K']); My questions is:
If I remove the following lines in the code:
helper(arr, res, i+1, slate); Once i is equal to 5 (which is the array.length), the code will stop after it pushes slate into res. However, if I leave that line in, a call stack is set up and so i will go up from 1->5, then pop out gradually to 4 then 3 then back to 4 and so on. Why does that happen?
Clarification: So I understand that for each recursion call, another i variable is generated. However, I was expecting the second recursion call to also generate i from 1->4 again, but this time instead of incrementing it linearly, there's backtracking going on as well. Why wasn't there backtracking in the first call, and why does the second call generate the rest of the results when the first call only generates the first result?
iis a local variable and each new execution ofhelperwill have its own version ofi, which can have a different value. When a recursive call returns, and the calling code continues, then its owniis relevant (again).ivariable is generated. However, I was expecting the second recursion call to also generateifrom 1->4 again, but this time instead of incrementing it linearly, there's backtracking going on as well. Why wasn't there backtracking in the first call, and why does the second call generate the rest of the results when the first call only generates the first result?i? It never does. If you look at the code, you see that there is no assignment toiever inhelper. The only thing that happens is thati+1is passed on to the recursive call, where it will become the initial and only value of the local variableithat only lives in that recursive execution context. When that execution terminates, we're back at the caller, where there is still the unchangediliving there.istops at 5. Then what happens next? Would1now be added toito make it6?