17、Letter Combinations of a Phone Number
電話號碼的字母組合
給定一個數字字符串,返回所有可能的字母組合,可以代表。
一個映射的數字字母(就像在電話裏按鈕)如下所示。
注意事項
以上的答案是按照詞典編撰順序進行輸出的,不過,在做本題時,你也可以任意選擇你喜歡的輸出順序。
給定 "23"
返回 ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
我的代碼:
class Solution {//遞歸形式,時間複雜度(3^n),空間複雜度(n)
public:
vector<string> const T={"","","abc","def",
"ghi","jkl","mno","pqrs","tuv","wxyz"};
vector<string> letterCombinations(string digits) {
vector<string> res;
if(digits.empty())return res;
dfs(res,"",0,digits);
return res;
}
void dfs(vector<string> &res,string s,int rank,string digits)
{
if(rank==digits.length())res.push_back(s);
else
for(auto c:T[digits[rank]-'0'])
dfs(res,s+c,rank+1,digits);
}
};
經典代碼:
// LeetCode, Letter Combinations of a Phone Number
// 時間複雜度O(3^n),空間複雜度O(1)
class Solution {
public:
const vector<string> keyboard { " ", "", "abc", "def", // '0','1','2',...
"ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
vector<string> letterCombinations (const string &digits) {
vector<string deep="9"> result(1, "");
for (auto d : digits) {
const size_t n = result.size();
const size_t m = keyboard[d - '0'].size();
result.resize(n * m);
for (size_t i = 0; i < m; ++i)
copy(result.begin(), result.begin() + n, result.begin() + n * i);
for (size_t i = 0; i < m; ++i) {
auto begin = result.begin();
for_each(begin + n * i, begin + n * (i+1), [&](string &s) {
s += keyboard[d - '0'][i];
});
}
}
return result;
}
};