【LeetCode】17. Letter Combinations of a Phone Number

来源:互联网 发布:2017最新一手数据 编辑:程序博客网 时间:2024/06/04 18:15

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.

Subscribeto see which companies asked this question.

分析

题意还是挺简单明了的,脑袋一抽想用递归的方法做,就是先求前n-1个的,再加上最后那个。其实没必要吧,递归肯定会多花时间的,还不如从前往后。  然后看了下leetcode的答案,有个建立临时vector在每次循环中跟ans swap的思路,特别巧妙。

自己的ac代码:

class Solution {public:void dp(int len, unordered_map<char, string> &mp, vector<string> &ans, const string& digits) {if (len >= 0) {dp(len - 1, mp, ans, digits);string tmp = mp[digits[len]];int endi = ans.size()-1;int j = 0;while (j<=endi) {for (int i = 0; i<tmp.size(); i++) {ans.push_back(ans[j] + tmp[i]);}j++;}++endi;while (endi--) ans.erase(ans.begin());}}vector<string> letterCombinations(string digits) {unordered_map<char, string> mp;mp['1'] = "1";mp['2'] = "abc";mp['3'] = "def";mp['4'] = "ghi";mp['5'] = "jkl";mp['6'] = "mno";mp['7'] = "pqrs";mp['8'] = "tuv";mp['9'] = "wxyz";mp['0'] = "0";mp['*'] = "*";mp['#'] = "#";        vector<string> ans;if(digits.empty()) return ans;ans.push_back("");dp(digits.size() - 1, mp, ans, digits);return ans;}};
利用swap的代码
using namespace std; vector<string> letterCombinations(string digits){ vector<string> ans; if(digits.empty()) return ans; ans.push_back("");  vector<string> v={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; for(int i=0;i<digits.size();i++){ int num=digits[i]-'0'; const string& candidate = v[num]; std::vector<string> tmp; for(int m=0;m<candidate.size();m++) for(int j=0;j<ans.size();j++){ tmp.push_back(ans[j]+candidate[m]); } ans.swap(tmp); } return ans; }

0 0