phone 个数字的字母组合
Letter combinations of a phone number
给定一个数字串,我们需要打印该数字代表的所有字母组合
对于输入“23”,输出应该是["ad"、"ae"、"af"、"bd"、"be"、"bf" , "cd", "ce", "cf"].
class Solution {
public:
char ph[10][4]={{'0','0','0','0',},{'0','0','0','0',},{'a','b','c','0'},{'d','e','f','0'},{'g','h','i','0'},{'j','k','l','0'},{'m','n','o','0'},{'p','q','r','s'},{'t','u','v','0'},{'w','x','y','z'}};
vector<string> ans;
void print(string digits,string st,int pos)
{
int i,l=digits.size();
if(l==pos)
{
ans.push_back(st);
return;
}
else
{
for(i=pos;i<l;i++)
{
int ch=digits[i]-'0';
for(int j=0;j<4 && ph[ch][j]!='0';j++)
{
print(digits,st+ph[ch][j],i+1);
}
}
}
}
vector<string> letterCombinations(string digits) {
int l=digits.size();
if(!l)
return ans;
print(digits,"",0);
return ans;
}
};
但是我得到一个输入“22”的错误,打印出 'a','b',c' additionally.What is wrong with the code?
问题是你在循环和递归。
print("22", "", 0);
将递归到
print("22", "a", 1);
print("22", "b", 1);
print("22", "c", 1);
print("22", "a", 2);
print("22", "b", 2);
print("22", "c", 2);
你的额外位是最后三个电话。
摆脱输入数字的循环(您已经通过递归执行了该步骤):
void print(string digits, string st, int pos)
{
if(digits.size() == pos)
{
ans.push_back(st);
}
else
{
int ch = digits[pos] - '0';
for(int j = 0; j < 4 && ph[ch][j] != '0'; j++)
{
print(digits, st + ph[ch][j], pos + 1);
}
}
}
(您还忘记了终止一些数组,但那是另一回事。)
给定一个数字串,我们需要打印该数字代表的所有字母组合
对于输入“23”,输出应该是["ad"、"ae"、"af"、"bd"、"be"、"bf" , "cd", "ce", "cf"].
class Solution {
public:
char ph[10][4]={{'0','0','0','0',},{'0','0','0','0',},{'a','b','c','0'},{'d','e','f','0'},{'g','h','i','0'},{'j','k','l','0'},{'m','n','o','0'},{'p','q','r','s'},{'t','u','v','0'},{'w','x','y','z'}};
vector<string> ans;
void print(string digits,string st,int pos)
{
int i,l=digits.size();
if(l==pos)
{
ans.push_back(st);
return;
}
else
{
for(i=pos;i<l;i++)
{
int ch=digits[i]-'0';
for(int j=0;j<4 && ph[ch][j]!='0';j++)
{
print(digits,st+ph[ch][j],i+1);
}
}
}
}
vector<string> letterCombinations(string digits) {
int l=digits.size();
if(!l)
return ans;
print(digits,"",0);
return ans;
}
};
但是我得到一个输入“22”的错误,打印出 'a','b',c' additionally.What is wrong with the code?
问题是你在循环和递归。
print("22", "", 0);
将递归到
print("22", "a", 1);
print("22", "b", 1);
print("22", "c", 1);
print("22", "a", 2);
print("22", "b", 2);
print("22", "c", 2);
你的额外位是最后三个电话。
摆脱输入数字的循环(您已经通过递归执行了该步骤):
void print(string digits, string st, int pos)
{
if(digits.size() == pos)
{
ans.push_back(st);
}
else
{
int ch = digits[pos] - '0';
for(int j = 0; j < 4 && ph[ch][j] != '0'; j++)
{
print(digits, st + ph[ch][j], pos + 1);
}
}
}
(您还忘记了终止一些数组,但那是另一回事。)