LeetCode || 递归 / 回溯

呜呜呜 递归好不想写qwq

17. Letter Combinations of a Phone Number

题意:在九宫格上按数字,输出所有可能的字母组合

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

思路:递归回溯求解

递归保存的是每层的状态,因此每层的 str 不应该改,而是更改str和idx后进入到下一层

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        int n = digits.length();
        if (n == 0) return {};
        vector<string> ans;
        string dict[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        dfs("", 0, dict, n, digits, ans);
        return ans;
    }
    void dfs(string str, int idx, string dict[], int n, string digits, vector<string> &ans) {
        if (idx == n) {
            ans.push_back(str);
            return;
        }
        if (digits[idx] <= '1' || digits[idx] > '9') return;
        for (int i = 0; i < dict[digits[idx] - '0'].length(); i++) {
            //str += dict[digits[idx] - '0'][i];
            dfs(str + dict[digits[idx] - '0'][i], idx + 1, dict, n, digits, ans);
        }
    }
};
View Code

猜你喜欢

转载自www.cnblogs.com/pinkglightning/p/10322241.html