这道题如果使用DFS比较简单,让人尴尬的是使用迭代反而实现有点小难度,可能平时刷题时侧重于DFS BFS,而较少练习迭代法的原因。
class Solution {
public:
vector<string> letterCombinations(string digits) {
if(digits.empty()) return {};
vector<string> res = {""};
for(auto digit:digits)
{
vector<string> temp;
for(auto candidate:pad[digit-'0'])
{
for(auto s:res)
temp.push_back(s+candidate);
}
//swap执行效率较高,赋值复杂度为O(n),swap复杂度为O(1)
//res = temp;
swap(res,temp);
}
return res;
}
private:
const vector<string> pad = {
"", "", "abc", "def", "ghi", "jkl",
"mno", "pqrs", "tuv", "wxyz"
};
};
执行效率:
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Letter Combinations of a Phone Number.
Memory Usage: 6.5 MB, less than 62.18% of C++ online submissions for Letter Combinations of a Phone Number.
BFS实现方式:
class Solution {
public:
vector<string> letterCombinations(string digits) {
if(digits.empty()) return {};
const vector<string> words{ " ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
deque<string> dq = {""};
for(auto digit:digits)
{
int size = dq.size();
for(int i = 0;i < size;i++)
{
string str = dq.front();
dq.pop_front();
for(auto c:words[digit-'0'])
{
dq.push_back(str+c);
}
}
}
return vector<string>(dq.begin(),dq.end());
}
};
运行结果:
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Letter Combinations of a Phone Number.
Memory Usage: 6.4 MB, less than 84.43% of C++ online submissions for Letter Combinations of a Phone Number.
上面的代码和BFS的套路代码非常像,也相对比较好理解。最后看下DFS的实现:
class Solution {
private:
int depth;
const vector<string> board={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
public:
vector<string> letterCombinations(string digits) {
if(digits.empty()) return {};
vector<string> res;
string ans;
depth = digits.size();
dfs(0,digits,ans,res);
return res;
}
private:
void dfs(int cur_dep,const string& digits,string ans,vector<string>& res)
{
if(depth == cur_dep)
{
res.push_back(ans);
return;
}
int num=digits[cur_dep]-'0';
for(int i=0;i<board[num].size();i++){
ans.push_back(board[num][i]);
dfs(cur_dep+1,digits,ans,res);
ans.pop_back();
}
}
};
运行效率:
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Letter Combinations of a Phone Number.
Memory Usage: 6.6 MB, less than 62.18% of C++ online submissions for Letter Combinations of a Phone Number.