《Programming Interviews Exposed》 中的一道递归题:Telephone number to words

题目:

电话键盘上通常一个数字会对应几个字母,如2->"ABC",3->“DEF”,等等,给定一个电话号码,输出所有可能的字母组合。如"866-2665"的一种字母组合是"TOOCOOL",要求输出全部。

解法:

与求前排列的递归类似。

#include <iostream>

#include <vector>
#include <string>

using namespace std;

class Solution {
public:
    void TelephoneWords( vector<string> & numberToLetter, string & number )
    {
        string words = "";
        PrintWords(numberToLetter, number, 0, words);
        return;
    }
    
    void PrintWords( vector<string> & numberToLetter, string & number, size_t start, string & words )
    {
        if(start == number.length())
        {
            cout << words << endl;
            return;
        }
        if( number[start]-'0' >= 0 )
        {
            for(size_t i = 0; i < numberToLetter[number[start]-'0'].length(); i++)
            {
                words.insert(words.end(), numberToLetter[number[start]-'0'][i]);
                PrintWords(numberToLetter, number, start+1, words);
                words.erase(words.length()-1, 1);
            }
        }
        else{
            words.insert(words.end(), '-');
            PrintWords(numberToLetter, number, start+1, words);
            words.erase(words.length()-1, 1);
        }
    }
};

int main(int argc, const char * argv[])
{

    // insert code here...
    vector<string> numberToLetter;
    numberToLetter.push_back("0");
    numberToLetter.push_back("1");
    numberToLetter.push_back("ABC");
    numberToLetter.push_back("DEF");
    numberToLetter.push_back("GHI");
    numberToLetter.push_back("JKL");
    numberToLetter.push_back("MNO");
    numberToLetter.push_back("PRS");
    numberToLetter.push_back("TUV");
    numberToLetter.push_back("WXY");
    
    string number = "497-1927";
    
    Solution s;
    s.TelephoneWords(numberToLetter, number);
    return 0;
}


你可能感兴趣的:(Algorithm)