LeetCode

来源:互联网 发布:qq飞车数据异常 编辑:程序博客网 时间:2024/06/01 07:13

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.

一个深搜,看来搜索的功力还木有退化地太惨,开森!

时间复杂度O(3^(digits.length())),空间复杂度O(1);

class Solution {public:    vector<string> mie{"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};    vector<string> ans;    vector<string> letterCombinations(string digits) {        if (digits == "") return ans;        solve(digits, 0, "");        return ans;    }    void solve(string digits, int id, string cur) {        if (id == digits.length()) {            ans.push_back(cur);            return;        }        int x = digits[id] - '0';        for (int i = 0; i < mie[x].length(); ++i) {            solve(digits, id+1, cur+mie[x][i]);        }    }};

原创粉丝点击