Leetcode17. Monogram telephone number [the TODO]

topic

Given a string contains only numeric characters 2-9, it can return all letter combinations indicated.
Given digital map to letters as follows (the same telephone key). Note 1 does not correspond to any alphabet.
Here Insert Picture Description

  • Example:
    Input: "23"
    Output: [ "ad", "ae ", "af", "bd", "be", "bf", "cd", "ce", "cf"].
  • Description:
    While the above answers are arranged in order according to the dictionary, but you can choose the order of the answer output.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/letter-combinations-of-a-phone-number
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

method

class Solution {
 //声明一个字典
  Map<String, String> phone = new HashMap<String, String>() {{
    put("2", "abc");
    put("3", "def");
    put("4", "ghi");
    put("5", "jkl");
    put("6", "mno");
    put("7", "pqrs");
    put("8", "tuv");
    put("9", "wxyz");
  }};
  //用来输出二维数组
  List<String> output = new ArrayList<String>();

  public void backtrack(String combination, String next_digits) {
    // if there is no more digits to check
    if (next_digits.length() == 0) {
      // the combination is done
      output.add(combination);
    }
    // if there are still digits to check
    else {
      // iterate over all letters which map 
      // the next available digit
      String digit = next_digits.substring(0, 1);
      String letters = phone.get(digit);
      for (int i = 0; i < letters.length(); i++) {
        String letter = phone.get(digit).substring(i, i + 1);
        // append the current letter to the combination
        // and proceed to the next digits
        backtrack(combination + letter, next_digits.substring(1));
      }
    }
  }

  public List<String> letterCombinations(String digits) {
    if (digits.length() != 0)
      backtrack("", digits);
    return output;
  }
}

Thinking

Next summary

Published 98 original articles · won praise 0 · Views 2690

Guess you like

Origin blog.csdn.net/qq_22017379/article/details/103952249