[Backtracking] [leetcode] letter combination of phone number

topic:

Given a string containing only the numbers 2-9, return all letter combinations it can represent. The answers can be returned in any order.

The mapping of numbers to letters is given as follows (same as phone buttons). Note that 1 does not correspond to any letters.

Example:

输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]

source:

17. Letter combination of phone number

Problem-solving ideas: backtracking

Define a path to record the letters put in each loop, and define a string array key to record the sequence of letters corresponding to each number.

  • Recursive termination condition: the size of the path is the same as the size of the input string
  • The result meets the condition: termination is output
  • Pruning conditions: none
static string key[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

class Solution {
public:
    vector<string> result;
    string path;
    vector<string> letterCombinations(string digits) {
        result.clear();
        path.clear();
        if (digits.empty()) return result;
        back(digits, 0);
        return result;
    }
    void back(const string& digits, int start) {
        if (path.size() == digits.size()) {
            result.push_back(path);
            return;
        }
        const string& p = key[digits[start] - '0'];
        for (int i = 0; i < p.size(); i++) {
            path.push_back(p[i]);
            back(digits, start+1);
            path.resize(path.size() - 1);
        }
    }
};

 

Guess you like

Origin blog.csdn.net/hbuxiaoshe/article/details/115008884