17. Letter Combinations of a Phone Number

来源:互联网 发布:联合电子汽车 知乎 编辑:程序博客网 时间:2024/06/02 06:00

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.
No.17 pic

Input:Digit string "23"Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
思路:
经典的backtracking(回溯算法)的题目。当一个题目,存在各种满足条件的组合,并且需要把它们全部列出来时,就可以考虑backtracking了。当然,backtracking在一定程度上属于穷举,所以当数据特别大的时候,不合适。而对于那些题目,可能就需要通过动态规划来完成。
  这道题假设输入的是”23”,2对应的是”abc”,3对应的是”edf”,那么我们在递归时,先确定2对应的其中一个字母(假设是a),然后进入下一层,穷举3对应的所有字母,并组合起来(”ae”,”ad”,”af”),当”edf”穷举完后,返回上一层,更新字母b,再重新进入下一层。这个就是backtracing的基本思想。

public class Solution {    public List<String> letterCombinations(String digits) {                String[] table = new String[]{"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};        List<String> list = new ArrayList<String>();                letterCombinations(list,digits,"",0,table);        return list;    }    private void letterCombinations (List<String> list, String digits, String curr, int index,String[] table) {                if (index == digits.length()) {            if(curr.length() != 0) list.add(curr);            return;        }        String temp = table[digits.charAt(index) - '0'];        for (int i = 0; i < temp.length(); i++) {                       String next = curr + temp.charAt(i);                       letterCombinations(list,digits,next,index+1,table);        }    }}