首页 > 其他 > 详细

[Leetcode]-- Letter Combinations of a Phone Number

时间:2014-02-05 12:42:12      阅读:327      评论:0      收藏:0      [点我收藏+]

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.

bubuko.com,布布扣

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

bubuko.com,布布扣
public class Solution {
    public ArrayList<String> letterCombinations(String digits) {
        ArrayList<String> result = new ArrayList<String>();
        if(digits.length() == 0){
            result.add("");
            return result;
        }
        
        String[] trans = new String[]{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        
        convert(trans, result, 0, digits, "");
        return result;
    }
    
    public void convert(String[] trans, ArrayList<String> result, int depth, String digits, String tmp){
        if(depth == digits.length()){
            result.add(tmp);
            return;
        }
        
        // ACSII码转int要减去48.
        int index = digits.charAt(depth) - 48;
        for(int i = 0; i < trans[index].length(); i++){
            tmp += trans[index].charAt(i);
            convert(trans, result, depth+1, digits, tmp);
            tmp = tmp.substring(0, tmp.length()-1);
        }
    }
}
bubuko.com,布布扣

 



ref:http://www.cnblogs.com/feiling/p/3185238.html

[Leetcode]-- Letter Combinations of a Phone Number

原文:http://www.cnblogs.com/RazerLu/p/3538150.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!