Letter Combinations of a Phone Number

来源:互联网 发布:淘宝客服日常工作内容 编辑:程序博客网 时间:2024/06/05 01:54


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.

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

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

Tag:回溯法。


char *letter[10];void func(string &str, vector<string> &ans, string digits, int index){    if(index == digits.size())    {        ans.push_back(str);        return;    }    int num = digits[index] - '0';    for(int i = 0; i < strlen(letter[num]); i++)    {        str += letter[num][i];        func(str, ans, digits, index+1);        str = str.substr(0, index);    }}vector<string> letterCombinations(string digits){    vector<string> ans;    ans.clear();    if(digits.size() == 0)    {        ans.push_back("");        return ans;    }    letter[0] = " ";    letter[1] = " ";    letter[2] = "abc";    letter[3] = "def";    letter[4] = "ghi";    letter[5] = "jkl";    letter[6] = "mno";    letter[7] = "pqrs";    letter[8] = "tuv";    letter[9] = "wxyz";    string str;    func(str, ans, digits, 0);    return ans;}


0 0
原创粉丝点击