|
| 1 | +/* |
| 2 | + * @lc app=leetcode id=17 lang=typescript |
| 3 | + * |
| 4 | + * [17] Letter Combinations of a Phone Number |
| 5 | + */ |
| 6 | + |
| 7 | +// @lc code=start |
| 8 | +/** |
| 9 | + * @description: 回溯的方式实现 |
| 10 | + * 其中 m 是输入中对应 3 个字母的数字个数(包括数字 2、3、4、5、6、8),nn 是输入中对应 4 个字母的数字个数(包括数字 7、9) |
| 11 | + * 时间复杂度 O(3m * 4n) |
| 12 | + * 空间复杂度 O(m + n) |
| 13 | + * @param {string} digits |
| 14 | + * @return {string[]} |
| 15 | + */ |
| 16 | +function letterCombinations(digits: string): string[] { |
| 17 | + const map = { |
| 18 | + 2: ['a', 'b', 'c'], |
| 19 | + 3: ['d', 'e', 'f'], |
| 20 | + 4: ['g', 'h', 'i'], |
| 21 | + 5: ['j', 'k', 'l'], |
| 22 | + 6: ['m', 'n', 'o'], |
| 23 | + 7: ['p', 'q', 'r', 's'], |
| 24 | + 8: ['t', 'u', 'v'], |
| 25 | + 9: ['w', 'x', 'y', 'z'], |
| 26 | + }; |
| 27 | + |
| 28 | + const len = digits.length; |
| 29 | + // 特殊情况的处理 |
| 30 | + if (len === 0) return []; |
| 31 | + |
| 32 | + if (len === 1) return map[digits[0]]; |
| 33 | + |
| 34 | + const ans = []; |
| 35 | + /** |
| 36 | + * @description: 回溯函数 |
| 37 | + * @param {string} str |
| 38 | + * @param {string[]} res |
| 39 | + * @param {number} len |
| 40 | + * @param {number} idx |
| 41 | + * @return {void} |
| 42 | + */ |
| 43 | + function backtrack(str: string, res: string[] = [], len: number, idx: number): void { |
| 44 | + if (str.length === len) { |
| 45 | + // 通过索引控制不同,因此不会有重复,可以直接添加 |
| 46 | + res.push(str); |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + for (let i = idx; i < len; i++) { |
| 51 | + const letterList = map[digits[i]]; |
| 52 | + |
| 53 | + // !回溯遍历,注意通过索引的变化来防止生成重复的结果 |
| 54 | + letterList.forEach((letter) => { |
| 55 | + backtrack(str + letter, res, len, i + 1); |
| 56 | + }); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + // 执行回溯方法 |
| 61 | + backtrack('', ans, len, 0); |
| 62 | + |
| 63 | + return ans; |
| 64 | +} |
| 65 | +// @lc code=end |
0 commit comments