您的位置:首页 > 其它

leetcode--17. Letter Combinations of a Phone Number

2016-08-07 13:00 621 查看
Letter Combinations of a Phone Number

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”].

题解

dfs

class Solution {
public:
vector<string> ans;
vector<string> letterCombinations(string digits) {
if(digits.empty()) return ans;
vector<string> dict{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
/*                  0   1     2      3      4      5      6       7      8       9    */
string prefix;
solve(prefix, digits, dict);
return ans;
}
void solve(string& prefix, string digits, vector<string>& dict){
if(digits.length() == 0){
ans.push_back(prefix);
return;
}
int idx = digits[0] - '0';
for(int i = 0; i < dict[idx].size(); ++i){
prefix.push_back(dict[idx][i]);
solve(prefix, digits.substr(1), dict);
prefix.pop_back();
}
}
};


BFS

public class Solution {
public List<String> letterCombinations(String digits) {
LinkedList<String> ans = new LinkedList<String>();
if(digits.length() == 0) return ans;
String[] mapping = new String[]{"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

ans.add("");
for(int i = 0; i < digits.length(); ++i){
int idx = digits.charAt(i) - '0';
while(ans.peek().length() == i){
String t = ans.remove();
for(char c : mapping[idx].toCharArray()) ans.add(t + c);
}
}
return ans;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode