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.
AC代码
class Solution {
public:
vector<string> letterCombinations(string digits) {
if (digits.size() == 0) return {};
vector<string> v{"abc", "def", "ghi", "jkl",
"mno", "pqrs", "tuv", "wxyz"};
int size = 1;
for (int i = 0; i < digits.size(); ++i)
size *= v[digits[i] - '0' - 2].size();
vector<string> ans(size);
int res = size;
for (int idx = 0; idx < digits.size(); ++idx) {
int len = v[digits[idx] - '0' - 2].size();
for (int i = 0; i < size; ++i) {
ans[i] += v[digits[idx] - '0' - 2][(i / (res / len)) % len]; #核心
}
res /= len;
}
return ans;
}
};
总结
网上有使用递归的解法,个人不是很懂递归的思想,有时间学习后再补充解法
网友评论