Letter Combinations of a Phone Number
DFS
int cnt[10] = {0,0,3,3,3,3,3,4,3,4};
char map[10][5] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
vector<string> letterCombinations(string digits) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int n = digits.size();
vector<string> result;
string path;
combination(0,n,digits,path,result);
return result;
}
void combination(int pos,int n,string& digits,string path,vector<string>& result)
{
if(pos == n)
{
result.push_back(path);
return;
}
int num = digits[pos]-'0';
if(cnt[num]>0)
{
for(int i=0;i<cnt[num];i++)
combination(pos+1,n,digits,path+map[num][i],result);
}else
combination(pos+1,n,digits,path,result);
}
浙公网安备 33010602011771号