Compute all mnemonics for a phone number


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值