您的位置:首页 > 其它

17. Letter Combinations of a Phone Number

2016-12-11 17:24 281 查看
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"].


class Solution {
public:
vector<string> letterCombinations(string digits) {
if(digits.empty()) return vector<string>();
static const vector<string> v = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> res;
res.push_back("");
for(int i = 0; i < digits.size(); ++i){
int m = digits[i]-'0';
if(m < 0 || m > 9) break;
const string& candidate = v[num];
if(candidate.empty()) continue;
vector<string> temp;

for(int k = 0; k < res.size(); ++k)
for(int j = 0; j < candidate.size(); ++j){
temp.push_back(res[k] + candidate[j]);
}
res.swap(temp);

}

return res;
}
};


第二种方法类似于深度遍历

class Solution {
public:
vector<string> letterCombinations(string digits)
{
vector<string> res;
if(digits.size()==0) return res;
string local;
vector<vector<char>> table(2,vector<char>());
table.push_back(vector<char>{'a','b','c'}); // index 2
table.push_back(vector<char>{'d','e','f'}); // 3
table.push_back(vector<char>{'g','h','i'});
table.push_back(vector<char>{'j','k','l'}); // 5
table.push_back(vector<char>{'m','n','o'});
table.push_back(vector<char>{'p','q','r','s'}); // 7
table.push_back(vector<char>{'t','u','v'});
table.push_back(vector<char>{'w','x','y','z'}); // 9

backtracking(table,res,local,0,digits);
return res;
}

void backtracking(const vector<vector<char>>& table, vector<string>& res, string& local, int index, const string& digits) {
if(index==digits.size())
res.push_back(local);
else
for(int i=0;i<table[digits[index]-'0'].size();i++) {
local.push_back(table[digits[index]-'0'][i]);
backtracking(table, res, local, index+1, digits);
local.pop_back();
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: