Letter Combinations of a Phone Number

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.
Letter Combinations of a Phone Number_第1张图片

Input:Digit string “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

#include "StdAfx.h"
#include <string>
#include <vector>
#include <iostream>

using namespace std;
class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> res;
        string trans[] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        size_t sz  = digits.size();
        //判断digits的长度是否为0,如果为0,则直接返回,如果不加判断,res中会有个空串,即res的长度为1
        if (0 == sz)
        {
            return res;
        }
        size_t n = 0;   //最开始处理第0个字符
        string seq;
        getLetterCombinations(digits,n,res,trans,seq);
        return res;
    }
    void getLetterCombinations(string &digits, size_t n, vector<string> &res,string *trans,string &seq)
    {
        //如果处理到尾端
        if (n == digits.size())
        {
            res.push_back(seq);
            return ;
        }
        for (size_t i = 0;i<trans[digits[n]-'0'].size();++i)
        {
            seq.push_back(trans[digits[n]-'0'][i]);
            getLetterCombinations(digits,n+1,res,trans,seq);
            //回溯
            seq.resize(seq.size()-1);
        }
    }
};
int main()
{
    Solution s;
    vector<string> vs;
    vs = s.letterCombinations("");
    cout<<vs.size()<<endl;
    for (vector<string>::iterator it=vs.begin();it!=vs.end();++it)
    {
        cout<<*it<<'\t';
    }
    return 0;
}

你可能感兴趣的:(算法)