美文网首页
[leetcode -- backtracking]Combin

[leetcode -- backtracking]Combin

作者: jowishu | 来源:发表于2016-10-22 13:57 被阅读7次

    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.
    Letter Combinations of a Phone Number

    解题思路:很显然这道题我们应该用暴力搜索来求解. 如果digits的长度是固定的(n), 则我们可以直接写一个n重for循环来解决. 但是现在的问题是digits的长度不是固定的, 因此我们也就不能直接用for循环来解决, 因为无法确定for循环的重数. 此时, 我们很容易想到回溯法, 因为回溯法实际上就是一个类似枚举的搜索尝试过程.

    首先根据数字与字母的映射关系, 我们建立映射表来保存这种映射关系. 然后递归的搜索满足条件(index==digits.size())的结果. 代码如下所示.

    class Solution {
    public:
        vector<string> letterCombinations(string digits) {
            vector<string> ret;
            if(digits.empty())
                return ret;
            vector<string> table = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
            string comb(digits.size(), 0);
            helper(0, table, comb, digits, ret);
            return ret;
        }
        
        void helper(int index, vector<string>& table, string& comb, string& digits, vector<string>& ret) {
            if(index == digits.size()) {
                ret.push_back(comb);
            }
            
            string letters = table[digits[index]-'0'];
            for(int i = 0; i < letters.size(); ++i) {
                comb[index] = letters[i];
                helper(index+1, table, comb, digits, ret);
            }
        }
    };
    

    相关文章

      网友评论

          本文标题:[leetcode -- backtracking]Combin

          本文链接:https://www.haomeiwen.com/subject/iachuttx.html