1. 程式人生 > >Leetcode 17 Letter Combinations of a Phone Number

Leetcode 17 Letter Combinations of a Phone Number

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中的元素進行新元素的新增,方法挺奇妙

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;
    }
}

時間複雜度:O(n3)