【LeetCode】 17. Letter Combinations of a Phone Number

来源:互联网 发布:北京哪里有mac专柜 编辑:程序博客网 时间:2024/05/01 10:46

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.

题目大意就是按手机上数字键,能组成多种字母组合,如“23”,2上面有abc 3上面有def,故可以组成

"ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"
这样的组合。

代码:

class Solution {private:    string num[10]={"","","abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};        vector<string> str;public:    void dfs(const string& digits,int l,string s){        int n=digits[l]-'0';        if (digits.size()==s.size()){            str.push_back(s);            return;        }        for(int i=0;i<num[n].size();++i)            dfs(digits,l+1,s+num[n][i]);    }    vector<string> letterCombinations(string digits) {        if (digits.size()==0) return str;        dfs(digits,0,"");        return str;    }};

从代码长度上来看比其他Medium的题目短不少,调试起来也不难,主要是想到用深度搜索的方法去解答。

0 0