题目:
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"].
思路:这也是一个排列组合的问题,一个数字对应着一个字符串,那么几个数字代表着几个字符串,把这几个数字代表的字符串组合起来,从这个组合后的字符串挑选几个字符(字符的个数就是数字的个数)
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/*
给一个电话数字,数字对应着不同的字符,对应着这些字符的组合,
组合个数对应着数字的个数
*/
void helper(string& str,int begin,vector<string>& hash,vector<char>& vec)
{
int i;
if(begin > str.length())
return;
if(begin == str.length())
{
for(i=0;i<vec.size();i++)
cout<<vec[i];
cout<<endl;
return;
}
for(i=0;i<hash[str[begin]-'0'].length();i++)
{
vec.push_back(hash[str[begin]-'0'][i]);
helper(str,begin+1,hash,vec);
vec.pop_back();
}
}
void Combination(string& str,vector<string>& hash)
{
if(str.length()==0)
return ;
vector<char> vec;
helper(str,0,hash,vec);
}
void LetterCom(string& str)
{
int i;
vector<string> hash(10); //这里假设有10个数字
hash[0]=" ";
hash[1]="-";
hash[2]="abc";
hash[3]="def";
hash[4]="ghi";
hash[5]="jkl";
hash[6]="mno";
hash[7]="pqrs";
hash[8]="tuv";
hash[9]="wxyz";
Combination(str,hash);
return ;
}
int main()
{
string str("23");
LetterCom(str);
return 0;
}
感觉这个题目还是很有水平的,不是单纯的组合,同时又是组合的变种,首先我们需要创建一个hash表,这个hash表内是根据号码索引对应号码所代表的字符串,对于一个数字字符串来说,我们需要从某一个数字对应的字符串中分别挑选一个字符,最终组合成一个字符串来表示组合,那么对于一个数字来说,我们就需要一个循环,然后递归处理下一个数字字符对应的字符串。