[LeetCode] 17. Letter Combinations of a Phone Number

来源:互联网 发布:动态寻路算法 编辑:程序博客网 时间:2024/05/29 06:28

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.

class Solution {public:    vector<string> letterCombinations(string digits) {        vector<string> res;        string str;        if (digits.size() > 0)            letterCombinations(res, str, digits, 0);        return res;    }private:    void letterCombinations(vector<string>& res, string& comb, string& digits, int nth) {        if (nth == digits.size()) {            res.push_back(comb);            return;        }        int digit = digits[nth] - '0';        for (auto letter : digit2letter[digit]) {            comb.push_back(letter);            letterCombinations(res, comb, digits, nth + 1);            comb.pop_back();        }    }    vector<vector<char>> digit2letter {        {' '},        {},        {'a', 'b', 'c'},        {'d', 'e', 'f'},        {'g', 'h', 'i'},        {'j', 'k', 'l'},        {'m', 'n', 'o'},        {'p', 'q', 'r', 's'},        {'t', 'u', 'v'},        {'w', 'x', 'y', 'z'},    };};

这里写图片描述这里写图片描述

原创粉丝点击