17. Letter Combinations of a Phone Number
Given a digit string, return all possible letter combinationsthat the number could represent.
A mapping of digit to letters (just like on the telephonebuttons) is given below.
用bfs遍历即可…
代码:
class Solution {
public:
stringstr[10] = { "",
"","abc","def",
"ghi","jkl","mno",
"pqrs","tuv","wxyz"};
vector<string>res;
vector<string>letterCombinations(string digits) {
if(digits.size()==0) return res;
charans[500];
bfs(digits,0, ans, 0);
returnres;
}
voidbfs(string digits, int digitsIndex, char *ans, int ansIndex) {
if(digitsIndex == digits.size()) {
ans[ansIndex]= '\0';
stringstr(ans);
res.push_back(str);
return;
}
inti = digits[digitsIndex] - '0';
for(int j = 0; j<str[i].size(); j++) {
ans[ansIndex]= str[i][j];
bfs(digits,digitsIndex + 1, ans, ansIndex + 1);
}
}
};