[leetcode] Letter Combinations of a Phone Number

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.

思路:

又是dfs的题目,dfs的时候,注意string一定要清除本次添加的元素。

题解:

class Solution {
public:
    vector<string> res;
    string tmp;
    void dfs(string digits, int index, string board[]) {
        if(index==digits.size()) {
            res.push_back(tmp);
            return;
        }
        string str = board[digits[index]-'0'];
        for(int i=0;i<str.size();i++) {
            tmp.push_back(str[i]);
            dfs(digits, index+1, board);
            tmp.pop_back();
        }
    }
    vector<string> letterCombinations(string digits) {
        string board[] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz",};
        dfs(digits,0, board);
        return res;
    }
};
View Code

后话:

每次这种题目我都是用的dfs,自己都烦了。来看看其他的牛逼方法吧。等着我在刷这题的时候尝试一下其他思路。

原文地址:https://www.cnblogs.com/jiasaidongqi/p/4221033.html