17. Letter Combinations of a Phone Number
- Total Accepted: 89600
- Total Submissions: 300111
- Difficulty: Medium
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.
思路:可以用回溯法,也可以直接先进先出地构造。这里注意c++中string数组的new方式。
代码:
FIFO构造:
1 class Solution { 2 public: 3 vector<string> letterCombinations(string digits) { 4 vector<string> v; 5 if(!digits.size()) return v; 6 string *mapping=new string[10]{"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 7 int n=digits.size(),i; 8 v.push_back(""); 9 for(i=0;i<n;i++){ 10 while(v[0].size()==i){ 11 string s=v[0]; 12 v.erase(v.begin()); 13 string temp=mapping[digits[i]-'0']; 14 for(int j=0;j<temp.size();j++){ 15 v.push_back(s+temp[j]); 16 } 17 } 18 } 19 return v; 20 } 21 };
回溯法:
1 class Solution { 2 public: 3 void letterCombinations(vector<string>& v,string digits,string s,string *mapping,int cur,int n){ 4 if(cur==n){ 5 v.push_back(s); 6 return; 7 } 8 int i,num=digits[cur]-'0'; 9 string temp=mapping[num]; 10 for(i=0;i<temp.size();i++){ 11 letterCombinations(v,digits,s+temp[i],mapping,cur+1,n); 12 } 13 } 14 vector<string> letterCombinations(string digits) { 15 vector<string> v; 16 int n=digits.size(); 17 if(!n) return v; 18 string *mapping=new string[10]{"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 19 letterCombinations(v,digits,"",mapping,0,n); 20 return v; 21 } 22 };