Leetcode 17 Letter Combinations of a Phone Number

HowieLee59發表於2018-10-13

Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

Example:

Input: "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.

這個題使用的迭代法,不斷的迭代list中的元素進行新元素的新增,方法挺奇妙

1)

class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> list = new ArrayList<>();
        String[] a = new String[]{" ","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        for(int i = 0 ; i < digits.length() ; i++){
            char[] arr = a[digits.charAt(i) - '0'].toCharArray();
            List<String> li = new ArrayList<>();
            if(list.isEmpty()){
                list.add("");
            }
            for(String s : list){
                for(int j = 0 ; j < arr.length;j++){
                    li.add(s + arr[j]);
                }
            }
            list = li;
        }
        return list;
    }
}

2)

public class Solution {
    
    List<String> res;
    
    public List<String> letterCombinations(String digits) {
        // 建立對映表
        String[] table = {" ", " ", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        StringBuilder tmp = new StringBuilder();
        res = new LinkedList<String>();
        helper(table, 0, tmp, digits);
        return res;
    }
    
    private void helper(String[] table, int idx, StringBuilder tmp, String digits){
        if(idx == digits.length()){
            // 找到一種結果,加入列表中
            if(tmp.length()!=0) res.add(tmp.toString());
        } else {
            // 找出當前位數字對應可能的字母
            String candidates = table[digits.charAt(idx) - '0'];
            // 對每個可能字母進行搜尋
            for(int i = 0; i < candidates.length(); i++){
                tmp.append(candidates.charAt(i));
                helper(table, idx+1, tmp, digits);
                tmp.deleteCharAt(tmp.length()-1);
            }
        }
    }
}

假設總共有n個digit,每個digit可以代表k個字元,那麼時間複雜度是O(k^n),就是結果的數量,空間複雜度也是一樣

方法二的參考連結-

相關文章