zoukankan      html  css  js  c++  java
  • [Leetcode]Letter Combinations of a Phone Numbers随记

    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;
        }
    }
    
    
  • 相关阅读:
    DLL文件的原理
    OD使用教程7(上) 调试篇07|解密系列
    复制独立数组的方法
    [转载 js] js正则表达式
    中国雅虎ued成员
    复制独立数组的方法
    [转载 js] js正则表达式
    以前做的flash相册
    编程的幽默
    我最早的全flash站
  • 原文地址:https://www.cnblogs.com/lilylee/p/5228594.html
Copyright © 2011-2022 走看看