17. Letter Combinations of a Phone Number
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.A mapping of digit to letters (just like on the telephone buttons) is giv..
·
Given a string containing digits from 2-9
inclusive, 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. Note that 1 does not map to any letters.
Example:
Input: "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.
class Solution {
public:
vector<string> letterCombinations(string digits) {
// 1 2 3 4 5 6 7 8 9
string d[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> v({""});
if(digits.empty()) return vector<string>();
for(int i = 0; i < digits.size(); ++ i)
{
vector<string> temp;
for(int j = 0; j < v.size(); ++ j)
for(int k = 0; k < d[digits[i] - '0'].size(); ++ k)
temp.push_back(v[j] + d[digits[i] - '0'][k]);
v = temp;
}
return v;
}
};
我自己做了相关的测试,并且记录了执行过程:
#include <iostream>
#include<vector>
#include<string>
using namespace std;
vector<string> letterCombinations(string digits) {
// 1 2 3 4 5 6 7 8 9
string d[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> v({""});
if(digits.empty()) return vector<string>();
for(int i = 0; i < digits.size(); ++ i)
{
vector<string> temp;
for(int j = 0; j < v.size(); ++ j)
for(int k = 0; k < d[digits[i] - '0'].size(); ++ k)
{temp.push_back(v[j] + d[digits[i] - '0'][k]);cout<<"v[j]="<<v[j]<<endl<<"d[digits[i] - '0'][k]="<<d[digits[i] - '0'][k]<<endl;}
v = temp;
}
return v;
}
int main()
{
vector<string>::iterator it;
vector<string> t;
t=letterCombinations("23");
for(it=t.begin();it!=t.end();it++)
cout << *it<<endl;
return 0;
}
v[j]=
d[digits[i] - '0'][k]=a
v[j]=
d[digits[i] - '0'][k]=b
v[j]=
d[digits[i] - '0'][k]=c
v[j]=a
d[digits[i] - '0'][k]=d
v[j]=a
d[digits[i] - '0'][k]=e
v[j]=a
d[digits[i] - '0'][k]=f
v[j]=b
d[digits[i] - '0'][k]=d
v[j]=b
d[digits[i] - '0'][k]=e
v[j]=b
d[digits[i] - '0'][k]=f
v[j]=c
d[digits[i] - '0'][k]=d
v[j]=c
d[digits[i] - '0'][k]=e
v[j]=c
d[digits[i] - '0'][k]=f
ad
ae
af
bd
be
bf
cd
ce
cf
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献1条内容
所有评论(0)