Guest User

Untitled

a guest
Aug 20th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. 'use strict';
  2.  
  3. // Solution to Question 17 "Letter Combinations of a Phone number using DFS backtracking"
  4.  
  5. const mappings = {
  6. 1: "",
  7. 2: "abc",
  8. 3: "def",
  9. 4: "ghi",
  10. 5: "jkl",
  11. 6: "mno",
  12. 7: "pqrs",
  13. 8: "tuv",
  14. 9: "wxyz"
  15. };
  16.  
  17. /**
  18. * @param {string} digits
  19. * @return {string[]}
  20. */
  21. var letterCombinations = function(digits) {
  22. if (digits == null || digits === "") {
  23. return [];
  24. }
  25. // initialize the result array
  26. let res = [];
  27. // keep track of the current index of digit we are looking at
  28. let currIdx = 0;
  29. // keep track of the current substring we are exploring
  30. let currStr = "";
  31. // start recursion
  32. backtracking(res, digits, currIdx, currStr);
  33. return res;
  34. };
  35.  
  36. var backtracking = function (res, digits, currIdx, currStr) {
  37. if (currIdx === digits.length) {
  38. // one of the solution now is complete, push it to the array
  39. return res.push(currStr);
  40. }
  41. // get the current character
  42. const c = digits[currIdx];
  43. // get its mapping
  44. const mapping = mappings[c];
  45. // iterate through every character in the mapping
  46. for (const s of mapping) {
  47. currStr += s;
  48. // recursion
  49. backtracking(res, digits, currIdx + 1, currStr);
  50. // revert currStr back
  51. currStr = currStr.slice(0, -1);
  52. }
  53. };
Add Comment
Please, Sign In to add comment