2017-09-10 LeetCode_017 Letter Combinations of a Phone Number

17. Letter Combinations of a Phone Number

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.

Solution:

vector<string> myans;
2
string sw[10] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
3
class Solution {
4
public:
5
    void deep(string & digits, int step, string now) {
6
        if (digits.length() == 0) return;
7
        if (step == digits.length()) {
8
            myans.push_back(now); return;
9
        }
10
        for (int i = 0; i < sw[digits[step]-'0'].length(); i++)
11
            deep(digits, step+1, now+sw[digits[step]-'0'][i]);
12
    }
13
    vector<string> letterCombinations(string digits) {
14
        myans.clear();
15
        deep(digits, 0, "");
16
        return myans;
17
    }
18
};






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章