码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode-Letter Combinations of a Phone Number

时间:2016-07-23 01:57:48      阅读:197      评论: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.

技术分享

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

public class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> result=new ArrayList<String>();
        if(digits==null || digits.length()==0){
            return result;
        }
        List<String> list=new ArrayList<String>();
        for(int i=0; i<digits.length(); i++){
            char c=digits.charAt(i);
            if(c==‘2‘){
                list.add("abc");
            }
            else if(c==‘3‘){
                list.add("def");
            }
            else if(c==‘4‘){
                list.add("ghi");
            }
            else if(c==‘5‘){
                list.add("jkl");
            }
            else if(c==‘6‘){
                list.add("mno");
            }
            else if(c==‘7‘){
                list.add("pqrs");
            }
            else if(c==‘8‘){
                list.add("tuv");
            }
            else if(c==‘9‘){
                list.add("wxyz");
            }
        }
        StringBuilder sb=new StringBuilder();
        dfs(list, 0, sb, result);
        return result;
    }
    public void dfs(List<String> inputs, int step,StringBuilder sb,List<String> res){
        if(step==inputs.size()){
            res.add(sb.toString());
            return;
        }
        String str=inputs.get(step);
        for(int i=0; i<str.length(); i++){
            sb.append(str.charAt(i));
            dfs(inputs, step+1, sb, res);
            sb.deleteCharAt(sb.length()-1);
        }
    }
}

  

Leetcode-Letter Combinations of a Phone Number

标签:

原文地址:http://www.cnblogs.com/incrediblechangshuo/p/5697694.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!