17. Letter Combinations of a Phone Number

每日一题 2019 - 03 - 07


题目:

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.

1

Example:

1
2
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.


解法:

这个题让我们找到给定电话号码上的所有不重复的排列组合,具体可以用三重循环的方法做,这三重循环的作用分别是:

  • 第一层遍历给定的string digits,因为我们要找到所有的待遍历电话数字
  • 第二层遍历待返回vector<string>,保证digits中的所有数据都能被遍历到,同时在遍历时候由于不能返回过程字符,所以要删除过程中遍历过的量
  • 第三层遍历digts中对应的每一个字母

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> res;
if (digits.empty()) return res;
string dict[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
res.push_back("");
for (int i = 0; i < digits.size(); ++i) {
int n = res.size();
string str = dict[digits[i] - '2'];
for (int j = 0; j < n; ++j) {
string tmp = res.front();
res.erase(res.begin());
for (int k = 0; k < str.size(); ++k) {
res.push_back(tmp + str[k]);
}
}
}
return res;
}
};
0%
undefined