您的位置:首页 > 编程语言 > C语言/C++

Leetcode 17. Letter Combinations of a Phone Number (Medium) (cpp)

2016-08-21 16:00 405 查看
Leetcode 17. Letter Combinations of a Phone Number (Medium) (cpp)

Tag: Backtracking, String

Difficulty: Medium

/*

17. Letter Combinations of a Phone Number (Medium)

Given a digit string, 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.

Input:Digit string "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.

*/
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> res;
if (digits.empty()) return res;
vector<string> letters = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
string s;
generate(digits, res, 0, s, letters);
return res;
}
void generate(string digits, vector<string>& res, int start, string s, vector<string>& letters) {
if (start == digits.length()) {
res.push_back(s);
return;
}
int num = digits[start] - '0';
for (int j = 0; j < letters[num].length(); j++) {
s.push_back(letters[num][j]);
generate(digits, res, start + 1, s, letters);
s.pop_back();
}
}
};

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode cpp