17.Letter Combinations of a Phone Number

来源:互联网 发布:程序员 团队贡献 编辑:程序博客网 时间:2024/06/06 00:45

17.Letter Combinations of a Phone Number

  • 题目描述:Given a digit string, return all possible letter combinations that the number could represent.A mapping of digit to letters (just like on the telephone buttons) is given below.

    这里写图片描述

    Input:Digit string "23"Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
  • 题目大意:给定一个数字字符串,返回所有计算器可以表述的String字符。

  • 思路:回溯

  • 代码

    package String;import java.util.LinkedList;import java.util.List;/*** @Author OovEver* @Date 2017/12/10 23:08*/public class LeetCode17 {  private static final String[] KEYS = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };  public List<String> letterCombinations(String digits) {      List<String> ret = new LinkedList<String>();      if(digits == null || digits.length() == 0) return ret;      combination("", digits, 0, ret);      return ret;  }  private void combination(String prefix, String digits, int offset, List<String> ret) {      if (offset == digits.length()) {          ret.add(prefix);          return;      }      String leeters = KEYS[digits.charAt(offset) - '0'];      for(int i=0;i<leeters.length();i++) {          combination(prefix + leeters.charAt(i), digits, offset + 1, ret);      }  }  public static void main(String[] args) {      LeetCode17 test = new LeetCode17();      System.out.println(test.letterCombinations(""));  }}
原创粉丝点击