【Leetcode】【Medium】Letter Combinations of a Phone Number
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
解题思路:
需要穷举不同中排列可能,典型需要回溯的思想;
可以选择递归或非递归的形式实现回溯;
递归:
1 class Solution { 2 public: 3 vector<string> letterCombinations(string digits) { 4 vector<string> lst; 5 string ans; 6 if (digits == "") 7 return lst; 8 Backtracking(lst, ans, digits, 0); 9 return lst; 10 } 11 12 void Backtracking(vector<string> &lst, string ans, string digits, int idx) { 13 if (idx == digits.size()) { 14 lst.push_back(ans); 15 return; 16 } 17 string cur_chars = d2l[digits[idx] - '0']; 18 for (int i = 0; i < cur_chars.size(); ++i) 19 Backtracking(lst, ans + cur_chars[i], digits, idx + 1); 20 } 21 22 private: 23 vector<string> d2l = { 24 " ", "", "abc", "def", "ghi", "jkl", 25 "mno", "pqrs", "tuv", "wxyz" 26 }; 27 };
非递归: