-
leetCode - Letter Combinations of a Phone Number(backtracking)프로그래밍/algorithm 2021. 7. 22. 09:26
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example 1:
Input: digits = "23" Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Example 2:
Input: digits = "" Output: []
Example 3:
Input: digits = "2" Output: ["a","b","c"]
Constraints:
- 0 <= digits.length <= 4
- digits[i] is a digit in the range ['2', '9'].
풀이
const letterCombinations = function (digits) { if (!digits.length) return ""; let result = []; let map = { 2: ['a', 'b', 'c'], 3: ['d', 'e', 'f'], 4: ['g', 'h', 'i'], 5: ['j', 'k', 'l'], 6: ['m', 'n', 'o'], 7: ['p', 'q', 'r', 's'], 8: ['t', 'u', 'v'], 9: ['w', 'x', 'y', 'z'], }; function backtrack(str, index) { if (index === digits.length) { result.push(str); return; } for (v of map[digits[index]]) { backtrack(str + v, index + 1); } } backtrack('', 0); return result; };
'프로그래밍 > algorithm' 카테고리의 다른 글
leetCode - Remove Nth Node From End of List (0) 2021.07.26 leetCode-4Sum(two pointer) (0) 2021.07.22 leetCode - 3Sum Closest (0) 2021.07.21 leetCode - 3sum (0) 2021.07.20 leetCode - Integer to Roman (0) 2021.07.20