如果字符串包含来自2-9的数字,则返回数字可以表示的所有可能的字母组合。按任何顺序返回答案。数字到字母的映射(就像在电话按钮上一样)如下所示。请注意,1不映射到任何字母。
Example 1:
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Example 2:
Input: digits = ""
Output: []
Example 3:
Input: digits = "2"
Output: ["a","b","c"]
一种基于DFS的简单方法。忽略一些用于我学习的注释(为了类似的问题,以便能够快速编写代码)。
#include
#include
#include
class Solution {
private:
// any auxilliary fields to help us (the "fluff" in the problem)
std::array mappings = {
"0", "1", "abc", "def", "ghi", "jkl",
"mno", "pqrs", "tuv", "wxyz"}; // note that 0 and 1 have the digits since
// that makes the most sense
// private functions that (may) do the heavy lifting
std::string_view getLettersMapping(char digit) {
return mappings[digit - '0'];
}
void dfs(std::vector &combinations, std::string_view digits,
std::string &s, size_t curr_idx, const size_t &N) {
// base case
if (curr_idx == N) {
// last digit's combination has already been explored, so simply append it
// to our set of combinations and return
combinations.push_back(s);
return;
}
// determine current mapping digit
auto letters = getLettersMapping(digits[curr_idx]);
// for that particular digit, generate all the possible combinations by
// recursing for each possible digit in the next index.
for (const auto &ch : letters) {
// note that passing the string s by reference saves space,
// but now we need to modify it by adding the letter and then removing the
// latest added later after the recursive call
s.push_back(ch);
dfs(combinations, digits, s, curr_idx + 1, N);
s.pop_back();
}
}
public:
std::vector letterCombinations(std::string digits) {
// in the main function, we develop the answer, call the "magic"
// recursion/DFS function, and return the answer
std::vector ans;
if (digits.empty() || digits.size() == 0) {
return ans;
}
std::string s;
dfs(ans, digits, s, 0, digits.size());
return ans;
}
};
对我的代码有什么建议吗?此外,我还在学习C++更“现代”的特性(任何从C++17开始的功能),所以任何这样的建议都是非常受欢迎的:
发布于 2020-11-29 13:31:24
mappings
static constexpr
此映射不应更改,因此理想情况下应该是constexpr
。您还只需要它的一个实例,所以它也应该被标记为static
(而且,constexpr
需要这个)。所以:
static constexpr std::array mappings = {
...
};
这也意味着getLetterMappings()
可以成为static constexpr
,而且实际上您也可以制作dfs()
static constexpr
,尽管constexpr
部分在那里做的并不多。
的冗余检查
为什么要同时检查digits.empty()
和digits.size() == 0
?这些表达方式是等价的。我只想检查一下digits.empty()
。
curr_idx
和N
由于要将输入数字以值形式传递给dfs()
,所以不需要参数curr_idx
和N
。只需将修改后的digits
版本传递给对dfs()
的递归调用,如下所示:
void dfs(std::vector &combinations, std::string_view digits, std::string &s) {
if (digits.empty()) {
combinations.push_back(s);
return;
}
auto letters = getLettersMapping(digits.front());
for (const auto &ch : letters) {
s.push_back(ch);
dfs(combinations, digits.substr(1), s);
s.pop_back();
}
}
https://codereview.stackexchange.com/questions/252798
复制相似问题