题目:
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.
题意:
还用得着解释?
思路:
DFS+回溯一波走~
Code:
class Solution {
public:
string g[11]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
vector<string> letterCombinations(string digits) {
vector<string> q;
if(digits.length()==0) return q;
string s;
dfs(q,s,digits,0);
return q;
}
void dfs(vector<string> &q,string &s,string &digits, int cur) {
if(cur>=digits.length()){
q.push_back(s);
return;
}
int t=digits[cur]-'0';
for(int i=0;i<g[t].length();i++){
char ch=g[t][i];
s.push_back(ch);
dfs(q,s,digits,cur+1);
s.pop_back();
}
}
};