17. Letter Combinations of a Phone Number | LeetCode Solution

 17. Letter Combinations of a Phone Number | LeetCode Solution


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 digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

 

Example 1:

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

Example 2:

Input: digits = ""
Output: []

Example 3:

Input: digits = "2"
Output: ["a","b","c"]

 

Constraints:

  • 0 <= digits.length <= 4
  • digits[i] is a digit in the range ['2', '9'].

The solution to the above question is -


class Solution
{
public:
  vector<string> ans;
  vector<string> letters = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
  void helper(string &s, int i, string t)
  {
    if (i == s.length())
    {
      ans.push_back(t);
      return;
    }
    for (auto c : letters[s[i] - '2'])
    {
      helper(s, i + 1, t + c);
    }
  }

  vector<string> letterCombinations(string digits)
  {
    if (digits == "")
      return ans;
    helper(digits, 0, "");

    return ans;
  }
};

Post a Comment

0 Comments