17. Letter Combinations of a Phone Number

题目链接

https://leetcode.com/problems/letter-combinations-of-a-phone-number/

解题思路

dfs找答案即可,具体见代码

代码

class Solution {
public:
    vector letterCombinations(string digits) {
        vector ans;
        if (digits.length() <= 0) {
            return ans;
        }
        
        vector table = { "abc",  "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        vector v;
        for (auto ch : digits) {
            v.push_back(table[ch - '2']);
        }
        
        dfs(ans, v, "", 0);
        return ans;
    }

    void dfs(vector &ans, vector &v, string s, int i) {
        if (i >= v.size()) {
            ans.push_back(s);
            return;
        }

        string cur = v[i];
        for (int k = 0; k < cur.length(); ++k) {
            dfs(ans, v, s + cur[k], i + 1);
        }
    }

};

你可能感兴趣的:(17. Letter Combinations of a Phone Number)