LeetCode-017 Letter Combinations of a Phone Number

来源:互联网 发布:蔡司三坐标测量机编程软件教程 编辑:程序博客网 时间:2024/06/06 19:28

Description

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

Example

A mapping of digit to letters (just like on the telephone buttons) is given below.
这里写图片描述
Input:Digit string “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

Analyse

这道题的背景也就是手机上的九宫格输入法假如根据它那个输入方式的话,能输出多少种结果,这也是一道简单的递归题,也不多解释。

Code

class Solution {public:    const string DIGIT[8]={"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};    void combination(vector<string> &ans,int pos,string &temp,string digits) {        if (pos==digits.length()) {            ans.push_back(temp);        } else {            int num=digits[pos]-'0';            for (int i=0;i<DIGIT[num-2].length();i++) {                temp=temp+DIGIT[num-2][i];                pos++;                combination(ans,pos,temp,digits);                pos--;                temp = temp.substr(0, temp.length()-1);            }        }    }    vector<string> letterCombinations(string digits) {        vector<string> ans;        if (digits=="") return ans;        string temp="";        combination(ans,0,temp,digits);        return ans;    }};