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"].

思路:递归解答

public class Solution {
    public String[] Keys =  { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
    public List<String> letterCombinations(String digits) {
        List<String> res = new ArrayList<String>();
        if (digits==null||digits.length()==0) return res;
        StringBuilder temp = new StringBuilder();
        traceBack(res, temp, digits, 0);
        return res;
    }

    public void traceBack(List<String> res,  StringBuilder temp, String digits, int startInd){
        if (startInd>=digits.length()){
            String sb = temp.toString();
            res.add(sb);
            return;
        }

        String letters = Keys[digits.charAt(startInd)-'0'];
        for (int i=0;i<letters.length();i++){
            temp.append(letters.charAt(i));
            traceBack(res, temp, digits, startInd+1);
            temp.deleteCharAt(temp.length()-1);
        }
    }
}

C++ code

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> res;
        if (digits.size()==0) return res;
        string temp;
        vector<vector<char>> table(2,vector<char>());
        table.push_back(vector<char>{'a','b','c'});
        table.push_back(vector<char>{'d','e','f'});
        table.push_back(vector<char>{'g','h','i'});
        table.push_back(vector<char>{'j','k','l'}); // 5
        table.push_back(vector<char>{'m','n','o'});
        table.push_back(vector<char>{'p','q','r','s'}); // 7
        table.push_back(vector<char>{'t','u','v'});
        table.push_back(vector<char>{'w','x','y','z'}); // 9

        backtracking(table, res, temp, 0, digits);
        return res;
    }

    void backtracking(vector<vector<char>>& table, vector<string>& res, string& temp, int index, string digits){
        if (index == digits.size()){
            res.push_back(temp);
        }else{
            for (int i=0; i<table[digits[index]-'0'].size(); i++){
                temp.push_back(table[digits[index]-'0'][i]);
                backtracking(table, res, temp, index+1, digits);
                temp.pop_back();
            }
        }
    }
};

results matching ""

    No results matching ""