Letter Combinations of a Phone Number, Leetcode 解题笔记

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.

200px-Telephone-keypad2.svg

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.

终于出现我最不擅长的递归题了,这道题是经典递归题,标准DFS解法,应作为模板牢牢记住。直接看code:

public class Solution {
    public ArrayList<String> letterCombinations(String digits) {
        String[] dic = {" ","", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        ArrayList<String> ret = new ArrayList<String>();
        StringBuilder temp = new StringBuilder(); 
        dfs(digits, dic, 0, temp, ret);
        return ret;
    }
    public void dfs(String digits, String[] dic, int deep, StringBuilder temp, ArrayList<String> ret){
        if(deep == digits.length()){
            ret.add(temp.toString());
            return;
        }
        else{
            for(int i = 0; i < dic[digits.charAt(deep) - '0'].length(); i++){
                temp.append(dic[digits.charAt(deep) - '0'].charAt(i));
                dfs(digits, dic, deep+1, temp, ret);
                temp.deleteCharAt(temp.length()-1);
            }
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s