您的位置:首页 > 编程语言 > C语言/C++

LeetCode之17_Letter Combinations of a Phone Number

2016-06-26 14:08 399 查看
题目原文:

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.

题意分析:

电话机上一个数字按键对应了多个字符,给出一个数字串,给出所有可能的字符串组合。

将对应关系放入map中后,直接深度搜索即可。

解题代码:

//Input:Digit string "23"
//Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
//通过输入的数字,输出可能的字母组合
//遍历所有情况,因为深度不确定,考虑使用递归,进行深度搜索

#include <iostream>
#include <vector>
#include <map>
using namespace std;

class Solution {
public:
map<char,string> num2Str;
char *pstr;
vector<string> vecBack;
vector<string> letterCombinations(string digits) {
vecInit(num2Str);
vecBack.clear();
pstr = (char*)malloc((1+digits.length())*sizeof(char));
if (pstr == NULL)
{
return vecBack;
}
if (digits.length()>0)
{
PushLetter(digits,0);
}

return vecBack;
}

void PushLetter(string digits, int Loc)
{
char szNum = digits[Loc];
string szPoss = num2Str[szNum];

for (int i=0; i<szPoss.length(); i++)
{
pstr[Loc] = szPoss[i];
if (Loc+1 < digits.length())
{
PushLetter(digits,Loc+1);
}
else if (Loc+1 == digits.length())
{
pstr[Loc+1] = '\0';
string sRet = pstr;
vecBack.push_back(sRet);
}
}
}

//初始化map中的对象
void vecInit(map<char,string> &vecInput)
{
vecInput.insert(make_pair('1',"@"));
vecInput.insert(make_pair('2',"abc"));
vecInput.insert(make_pair('3',"def"));
vecInput.insert(make_pair('4',"ghi"));
vecInput.insert(make_pair('5',"jkl"));
vecInput.insert(make_pair('6',"mno"));
vecInput.insert(make_pair('7',"pqrs"));
vecInput.insert(make_pair('8',"tuv"));
vecInput.insert(make_pair('9',"wxyz"));
vecInput.insert(make_pair('0',"_"));
vecInput.insert(make_pair('*',"+"));
//vecInput.insert(make_pair(''))
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ leetcode 组合