17. 电话号码的字母组合(回溯/DFS)
Posted Ston.V
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了17. 电话号码的字母组合(回溯/DFS)相关的知识,希望对你有一定的参考价值。
1.Description
2.Example
示例 1:
输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例 2:输入:digits = ""
输出:[]
示例 3:输入:digits = "2"
输出:["a","b","c"]
3. Code
回溯法(DFS):回溯都是一个模板,写几遍就晓得了。某处有多种选择时,for遍历;开始一轮后先检查边界条件收集结果,结束一轮后回退。
class Solution
public:
map<char,string> m=
'2',"abc",'3',"def",'4',"ghi",'5',"jkl",'6',"mno",'7',"pqrs",'8',"tuv",'9',"wxyz"
;
int index =0;
vector<string> res;
string s = "";
vector<string> letterCombinations(string digits)
int n = digits.length();
if(n==0)
return res;
DFS(digits,index,s);
return res;
void DFS(string digits,int index,string &s)
if(index == digits.length())
res.push_back(s);
return;
else
for(char c:m[digits[index]])
s.push_back(c);
DFS(digits,index+1,s);
s.pop_back();
;
以上是关于17. 电话号码的字母组合(回溯/DFS)的主要内容,如果未能解决你的问题,请参考以下文章