题目出处:https://leetcode.com/problems/letter-combinations-of-a-phone-number/
计算输入字母组合
例子:
Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
分析:
两种方法解决:
1. 预先计算总长度,逐个更新字母。 以"23"为例输出的结果是:
a | d |
a | e |
a | f |
b | d |
b | e |
b | f |
c | d |
c | e |
c | f |
2. 递增求解, 以“23”为例, 输出的结果是
a | d |
b | d |
c | d |
a | e |
b | e |
c | e |
a | f |
b | f |
c | f |
算法1代码:
vector<string> letterCombinations(string digits) {
// cout<< digits.length() <<endl;
if(digits.length() <= 0) return vector<string>();
string tag[10] = {"", "hX", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
//count length
int length = 1;
for(int i = 0; i < digits.length(); i++){
int n = digits[i] == '#' ? 1 : digits[i] - '0';
length *= tag[n].length();
}
vector<string> ret(length, string(digits.length(), '\0'));
int curLength = length;
for(int i = 0; i < digits.length(); i++){
// get index
int n = digits[i] == '#' ? 1 : digits[i] - '0';
curLength /= tag[n].length();
for(int j = 0; j < length; j++){
ret[j][i] = tag[n][j/curLength%tag[n].length()];
}
}
return ret;
}
算法2代码:
vector<string> letterCombinations(string digits) {
if(digits.length() <= 0) return vector<string>();
string tag[10] = {"", "hX", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> ret;
for(int i = 0; i < digits.length(); i++){
int n = digits[i] == '#' ? 1 : digits[i] - '0';
int size = ret.size() == 0 ? 1 : ret.size();
ret.resize(size * tag[n].length());
for(int j = ret.size()-1; j >= 0; j--)
ret[j] = ret[j%size] + tag[n][j/size];
}
return ret;
}