一、题目:
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"].
二、分析:
这道题的要求是给定一个数字字符串,返回手机键盘上对应的所有可能的字母组合。其中返回的顺序可以是任意的。
这道题的思路比较简单,可以迭代,即依次读取字符串中的每位数字,然后把数字对应的字母依次加到当前的所有结果中,然后进入下一次迭代。。假设输入字符串总共有n个数字,平均每个数字可以代表m个字符,那么时间复杂度是O(m^n),确切点是输入字符串中每个数字对应字母数量的乘积,即结果的数量,空间复杂度也是一样。
时间复杂度:O(m^n)
空间复杂度:O(m^n)
三、解题:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
vector<string> letterCombinations(string digits) {
vector<string> result;
if (digits.empty()) return vector<string>();
static const vector<string> v = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
result.push_back(""); // 使得大小为一好初始化
for (int i = 0; i < digits.size(); ++i) {
int num = digits[i] - '0';
if (num < 0 || num > 9) break;
const string& candidate = v[num];//得到该数字对应的字符串
if (candidate.empty()) continue;
vector<string> tmp;
for (int j = 0; j < candidate.size(); ++j) {
for (int k = 0; k < result.size(); ++k) {
tmp.push_back(result[k] + candidate[j]);
}
}
result.swap(tmp);
}
return result;
};
int main()
{
vector<string> s=letterCombinations("23");
for (int i = 0; i < s.size(); i++)
{
cout<< s[i] << ' ';
}
system("pause");
}