Week9: Letter Combinations of a Phone Number
Difficulty:Medium
1.Problem
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.
2.Algorithm
举例:如果input为”23”,因为 2 = “abc”, 3 = “def”,我们可以从最小的字符串”ad”开始,然后变为”ae”, “af”,此时我们可以将最后一个字符 从”f” 变为 “d” ,接着我们可以从 “bd”, “be”, “bf”…继续下去。这样可以避免递归。
3.Solution
class Solution {
public:
vector<string> letterCombinations(string digits) {
int size = digits.size();
string phone[8] = {"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
vector<string> ans;
if(size == 0) return ans;
string S = "";
for(int i = 0; i < size; i++) {
S += phone[digits[i]-'0'-2][0];
}
ans.push_back(S);
vector<int> v(size,0);
while(true) {
int j = size - 1;
v[j]++;
while(j > 0 && v[j] == phone[digits[j]-'0'-2].length()) {
v[j] = 0;
S[j] = phone[digits[j]-'0'-2][0];
j--;
v[j]++;
}
if(v[0] == phone[digits[0]-'0'-2].length()) break;
else S[0] = phone[digits[0]-'0'-2][v[0]];
S[j] = phone[digits[j]-'0'-2][v[j]];
ans.push_back(S);
}
return ans;
}
};