Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 17. Letter Combinations of a Phone Number

Rain Hu

17. Letter Combinations of a Phone Number


一、題目

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
1200px-telephone-keypad2svg

Example 1:

Example 2:

Example 3:

Constraints:


二、分析

三、解題

1. Backtracking

vector<string> letterCombinations(string digits) {
    vector<string> dict = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};   // 選項
    vector<string> res;
    if (digits.empty()) return res;
    string path;        // 路徑
    backtrack(dict, res, path, digits);
    return res;
}
void backtrack(vector<string> dict, vector<string>& res, string& path, string& digits) {
    if (path.length() == digits.length()) {     // 終止條件
        res.push_back(path);                    // 記錄路徑
        return;
    }
    int i = path.size();
    string letters = dict[digits[i] - '0'];
    for (char letter : letters) {
        path.push_back(letter);               // 做選擇
        backtrack(dict, res, path, digits);
        path.pop_back();                      // 撤銷選擇
    }
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 18. 4Sum
Next
[LeetCode] 16. 3Sum Closet