Letter Combinations of a Phone Number

Letter Combinations of a Phone Number 

问题:

iven 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.

思路:

  dfs+回溯

我的代码:

public class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> list = new ArrayList<String>();
        if(digits == null || digits.length() == 0)  return list;
        helper("", digits, list);
        return list;
    }
    public void helper(String s, String digits, List<String> list)
    {
        if(digits.length() == 0)
        {
            list.add(s);
            return;
        }
        char digit = digits.charAt(0);
        String letters = getLetters(digit);
        if(letters.equals(""))
        {
            helper(s, digits.substring(1), list);
        }
        for(int i = 0; i <letters.length(); i++)
        {
            helper(s+letters.charAt(i), digits.substring(1), list);
        }
    }
    public String getLetters(char c)
    {
        switch(c)
        {
            case '2': return "abc";
            case '3': return "dfe";
            case '4': return "ghi";
            case '5': return "jkl";
            case '6': return "mno";
            case '7': return "pqrs";
            case '8': return "tuv";
            case '9': return "wxyz";
            default : return "";
        }
    }
}
View Code

他人代码:

public class Solution {
    public ArrayList<String> letterCombinations(String digits) {
        ArrayList<String> result = new ArrayList<String>();

        if (digits == null) {
            return result;
        }

        Map<Character, char[]> map = new HashMap<Character, char[]>();
        map.put('0', new char[] {});
        map.put('1', new char[] {});
        map.put('2', new char[] { 'a', 'b', 'c' });
        map.put('3', new char[] { 'd', 'e', 'f' });
        map.put('4', new char[] { 'g', 'h', 'i' });
        map.put('5', new char[] { 'j', 'k', 'l' });
        map.put('6', new char[] { 'm', 'n', 'o' });
        map.put('7', new char[] { 'p', 'q', 'r', 's' });
        map.put('8', new char[] { 't', 'u', 'v'});
        map.put('9', new char[] { 'w', 'x', 'y', 'z' });

        StringBuilder sb = new StringBuilder();
        helper(map, digits, sb, result);

        return result;
    }

    private void helper(Map<Character, char[]> map, String digits, 
        StringBuilder sb, ArrayList<String> result) {
        if (sb.length() == digits.length()) {
            result.add(sb.toString());
            return;
        }

        for (char c : map.get(digits.charAt(sb.length()))) {
            sb.append(c);
            helper(map, digits, sb, result);
            sb.deleteCharAt(sb.length() - 1);
        }
    }
}
View Code

学习之处:

  • string 自带回溯属性 这方面减少不少的问题 不断的新建s 消耗的空间还是挺多的。
  • 他人代码里面用的是StringBuffer相对而言,节约了空间。
原文地址:https://www.cnblogs.com/sunshisonghit/p/4339892.html