8.6—暴力枚举法—Letter Combinations of a Phone Number

来源:互联网 发布:linux下的下载工具 编辑:程序博客网 时间:2024/05/28 22:12
描述
Given a digit string, return all possible leer combinations that the number could represent.
A mapping of digit to leers (just like on the telephone buons) 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.



#include<iostream>#include<vector>#include<string>#include<algorithm>using namespace std;vector<string> key_map = { " ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };vector<string> LetterCombinations(string digits){vector<string> res;res.push_back("");if (digits.size() <= 0)return res;sort(digits.begin(), digits.end());string::iterator iter = unique(digits.begin(), digits.end());digits.erase(iter,digits.end());string mydigits;for (int i = 0; i < digits.size(); i++){if (digits[i] != '1')mydigits.push_back(digits[i]);}//===for (int i = 0; i < mydigits.size(); i++){vector<string> tempres;string chars = key_map[mydigits[i] - '0'];for (int j = 0; j < chars.size(); j++){for (int k = 0; k < res.size(); k++)tempres.push_back(res[k] + chars[j]);}res = tempres;}return res;}int main(){string digits = "123";vector<string> res = LetterCombinations(digits);for (int i = 0; i < res.size(); i++)cout << res[i] << endl;}

阅读全文
0 0
原创粉丝点击