Leetcode 17. Letter Combinations of a Phone Number

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Leetcode 17. Letter Combinations of a Phone Number_第1张图片
Letter Combinations of a Phone Number

2. Solution

class Solution {
public:
    vector letterCombinations(string digits) {
        vector result;
        int n = digits.length();
        if(n == 0) {
            return result;
        }
        map m = { 
            {'2', "abc"}, 
            {'3', "def"}, 
            {'4', "ghi"}, 
            {'5', "jkl"}, 
            {'6', "mno"}, 
            {'7', "pqrs"}, 
            {'8', "tuv"}, 
            {'9', "wxyz"}
        };
        vector values;
        for(char ch : digits) {
            values.push_back(m[ch]);
        }
        traverse(result, values, n, 0, "");
        return result;
    }

private:
    void traverse(vector& result, vector& values, int& n, int current, string s) {
        if(current == n) {
            result.push_back(s);
            return;
        }
        for(char ch : values[current]) {
            string temp = s;
            temp += ch;
            traverse(result, values, n, current + 1, temp);
        }
    }
};

Reference

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

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