[LeetCode] 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模板,这和 Sudoku solver 的思路基本没有差别(其实和所有类似的题型都没差,几乎都用DFS模板一套就能出来)

void comboIter(string digits, int i, vector<string> &domains, string cur, vector<string> &result) {
    if (i >= digits.size()) {
        result.push_back(cur);
        return;
    }
    char t = digits.at(i);
    string domain = domains[t-'0'];
    string old = cur;
    for (char ele : domain) {
        cur += ele;
        comboIter(digits, i+1, domains, cur ,result);
        cur = old;
    }
}

vector<string> letterCombinations(string digits) {
    vector<string> ret;
    if (!digits.size()) return {""};
    vector<string> domain = {"0","1","abc","def","ghi","jkl","mno","pqr","stu","vwxyz"};
    comboIter(digits,0,domain,"",ret);
    return ret;
}

 

posted @ 2014-12-10 23:35  Agentgamer  阅读(164)  评论(0编辑  收藏  举报