您的位置:首页 > 其它

Letter Combinations of a Phone Number

2015-09-08 00:10 337 查看


Letter Combinations of a Phone Number

Total Accepted: 51210 Total
Submissions: 200367My Submissions

Question
Solution

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.

class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> re;
string str = "";
char *tel[] = {"abc","def","ghi","jkl","mno","pqrs","tvu","wxyz"};
int n = digits.length();
if(!n)
return re;
Combination( re, str, tel, n,digits);
return re;
}
void Combination(vector<string> &re,string str,char * *tel,int n,string digits)
{
if(n == 0)
{
re.push_back(str);
return;
}else
{
string ori = str;
char tmp = digits[digits.length() - n] - '2';
if( tmp == 5 || tmp == 7) //4c次循环
{
for( int i = 0; i < 4; i ++)
{
char ch = tel[tmp][i];
str = ori + ch;
Combination( re,str,tel,n-1,digits);
}
}else//3次循环
{
for( int i = 0; i < 3; i ++)
{
char ch = tel[tmp][i];
str = ori + ch;
Combination( re,str,tel,n-1,digits);
}
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: