Elements of Programming Interviews 7.3 题目
手机的数字按键都对应0-4个字母,输入一串数字(10位),打印所有可能的字母组合
思路: 10层for 循环,每层内遍历各对应的字母,即可。共1*1*3*3*3*3*3*3*4*4 case;
转换成递归,10层嵌套!
1 #include <string>
2 #include <array>
3 #include <iostream>
4
5 using namespace std;
6
7 const int kNumTelDigits = 10;
8
9 const array<string, kNumTelDigits> M = { {"0", "1", "ABC", "DEF", "GHI",
10 "JKL", "MNO", "PQRS", "TUV",
11 "WXYZ"} };
12
13 void phone_mnemoic_helper(const string& num, int d, string* ans)
14 {
15 if(d==num.size()) //
16 {
17 cout << *ans << endl;
18 }
19 else
20 {
21 for(const char& c : M[num[d] - '0'])
22 {
23 (*ans)[d] = c;
24 phone_mnemoic_helper(num, d+1, ans);
25 }
26 }
27 }
28
29 void phone_mnemonic(const string &num)
30 {
31 string ans(num.size(), 0);
32 phone_mnemoic_helper(num, 0, &ans);
33 }
34
35 int main()
36 {
37 const string cellnumber = "7169076520";
38 phone_mnemonic(cellnumber);
39
40 return 0;
41 }
42
从今天开始,每天做几道算法题 may 30