Leetcode 17. Letter Combinations of a Phone Number (Medium) (cpp)

来源:互联网 发布:农夫山泉瓶子尺寸数据 编辑:程序博客网 时间:2024/05/29 21:31

Leetcode 17. Letter Combinations of a Phone Number (Medium) (cpp)

Tag: Backtracking, String

Difficulty: Medium


/*17. Letter Combinations of a Phone Number (Medium)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;        if (digits.empty()) return res;        vector<string> letters = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};        string s;        generate(digits, res, 0, s, letters);        return res;    }    void generate(string digits, vector<string>& res, int start, string s, vector<string>& letters) {        if (start == digits.length()) {            res.push_back(s);            return;        }        int num = digits[start] - '0';        for (int j = 0; j < letters[num].length(); j++) {            s.push_back(letters[num][j]);            generate(digits, res, start + 1, s, letters);            s.pop_back();        }    }};


0 0