您的位置:首页 > 其它

[LeetCode] Letter Combinations of a Phone Number

2017-12-03 14:37 429 查看
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.

该题的主要意思:给你2-9数字中的任意几个,其中每个数字都包含三个字母,其所包含的字母如上图所示,求出这些数字所构成的所有组合。

该种题型较为简单,我们可以通过深度优先遍历求解。

深度优先遍历算法如下:

复杂度:时间
O(n2)递归栈空间

思路:首先建一个表,来映射号码和字母的关系。然后对号码进行深度优先搜索,对于每一位,从表中找出数字对应的字母,这些字母就是本轮搜索的几种可能。

char str[1000];
vector<string>result;
class Solution {
public:
vector<string> letterCombinations(string digits) {
int len = digits.size();
if (len == 0)
return result;
string nums[] = {" ", " ", "ab", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
digitsDeal(digits, 0, len, nums);
return result;
}
public:
void digitsDeal(string &digits, int i, int len, string *nums)
{
if(i == len)
{
str[len] = '\0';
string temp = str;
result.push_back(temp);
return;
}

int index = digits[i]-'0';
for(int j= 0; j < nums[index].size(); ++j)
{
str[i] = nums[index][j];
digitsDeal(digits, i+1, len, nums);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: