lintcode-425-電話號碼的字母組合


425-電話號碼的字母組合

Given a digit string excluded 01, 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.

注意事項

以上的答案是按照詞典編撰順序進行輸出的,不過,在做本題時,你也可以任意選擇你喜歡的輸出順序。

樣例

給定 "23"
返回 ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]

標簽

遞歸 回溯法 字符串處理 臉書 優步

思路

使用回溯 + 遞歸

code

class Solution {
public:
    /*
     * @param digits: A digital string
     * @return: all posible letter combinations
     */
    vector<string> letterCombinations(string digits) {
        // write your code here
        if (digits.size() <= 0) {
            return vector<string>();
        }
        vector<string> result;
        string str;
        letterCombinations(digits, str, 0, result);
        return result;
    }

    void letterCombinations(string &digits, string &str, int index, vector<string> &result) {
        if (index == digits.size()) {
            result.push_back(str);
            return;
        }
        string base[] = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
        for (int i = 0; i < base[digits[index] - '0'].size(); i++) {
            str += base[digits[index] - '0'][i];
            letterCombinations(digits, str, index + 1, result);
            str.pop_back();
        }
    }
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM