17. 电话号码的字母组合
题目连接:17. 电话号码的字母组合(中等)
给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1:
输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例 2:
输入:digits = ""
输出:[]
示例 3:
输入:digits = "2"
输出:["a","b","c"]
提示:
-
0 <= digits.length <= 4
-
digits[i]
是范围['2', '9']
的一个数字。
解题思路
首先是“数字与字母之间的映射”,可以用一个 string 类型的数组 或者 map 来实现。另外就是用“回溯算法”来实现题中的多个 for 循环。
C++
class Solution { public: const string letterMap[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; vector<string> result; string path; void backTracking(string digits, int index) { if (path.size() == digits.size()) { // 终止条件(拼接字符串的长度 等于 数字字符串的长度) result.push_back(path); return; } string letter = letterMap[digits[index] - '0']; for (int i = 0; i < letter.size(); i++) { path.push_back(letter[i]); backTracking(digits, index + 1); path.pop_back(); } } vector<string> letterCombinations(string digits) { path.clear(); result.clear(); if(digits.size() == 0) return result; backTracking(digits, 0); return result; } };
JavaScript
const letterMap = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]; let path = []; let result = []; const backTracking = (digits, index) => { if (path.length == digits.length) { result.push(path.join("")); return; } let k = digits[index] - '0'; let letter = letterMap[k]; for (let i = 0; i < letter.length; i++) { path.push(letter[i]); backTracking(digits, index + 1); path.pop(); } } var letterCombinations = function(digits) { result = []; path = []; if (digits.length === 0) return result; backTracking(digits, 0); return result; };