首页 > 其他 > 详细

[Leetcode]Letter Combinations of a Phone Numbers随记

时间:2016-02-29 19:54:19      阅读:191      评论:0      收藏:0      [点我收藏+]

No.17, Letter Combinations of a Phone Numbers

技术分享

根据输入的数字,输出所有可能的字母组合。例如输入“23”,输出["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]

这里采用了简单的递归方式来做,也可以说是dfs吧(感觉还是有点不太像?)。每次都把第一个数字可能的字符拿出来,和后面n-1的可能字符串进行枚举拼接,有几个数字就递归几次。还有可以用栈的方式实现(用循环代替递归)。当然时间复杂度上都差不多。

public class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> result;
        String[] map = new String[10];  
        map[0] = "";  
        map[1] = "";  
        map[2] = "abc";  
        map[3] = "def";  
        map[4] = "ghi";  
        map[5] = "jkl";  
        map[6] = "mno";  
        map[7] = "pqrs";  
        map[8] = "tuv";  
        map[9] = "wxyz"; 
        result=dfs(digits,map);
        return result;
    }
    public List<String> dfs(String digits,String[] map){
        List<String> result=new ArrayList<String>();
        if(digits.isEmpty()){
            return result;
        }
        int number=digits.charAt(0)-‘0‘;
        String c=map[number];
        List<String> next=dfs(digits.substring(1),map);
        for(int i=0;i<c.length();i++){
            if(next.isEmpty()){
                result.add(c.charAt(i)+"");
            }
            for(int j=0;j<next.size();j++){
                result.add(c.charAt(i)+next.get(j));
            }
        }
        return result;
    }
}

 

[Leetcode]Letter Combinations of a Phone Numbers随记

原文:http://www.cnblogs.com/lilylee/p/5228594.html

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