【LeetCode】17. 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.

【LeetCode】17. Letter Combinations of a Phone Number_第1张图片

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 &mp, vector &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 letterCombinations(string digits) {
	unordered_map 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 ans;
	if(digits.empty()) return ans;
	ans.push_back("");
	dp(digits.size() - 1, mp, ans, digits);
	return ans;
}
};
利用swap的代码
using namespace std;
 vector letterCombinations(string digits){
 	vector ans;
 	if(digits.empty()) return ans;
 	ans.push_back(""); 
 	vector v={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
 	for(int i=0;i tmp;
 		for(int m=0;m

你可能感兴趣的:(leetcode)