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

Letter Combinations of a Phone Number——LeetCode

时间:2015-04-06 15:30:40      阅读:107      评论: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"].

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

 

题目大意:给一组数字,按照电话键盘上的组合输出所有的可能。

解题思路:直接递归写DFS,输出所有组合。

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class LetterCombinationsofaPhoneNumber {

    public static void main(String[] sure) {
        new LetterCombinationsofaPhoneNumber().letterCombinations("213");
    }

    static Map<Character, String> mapping = new HashMap<>();

    static {
        mapping.put(‘0‘, "");
        mapping.put(‘1‘, "");
        mapping.put(‘2‘, "abc");
        mapping.put(‘3‘, "def");
        mapping.put(‘4‘, "ghi");
        mapping.put(‘5‘, "jkl");
        mapping.put(‘6‘, "mno");
        mapping.put(‘7‘, "pqrs");
        mapping.put(‘8‘, "tuv");
        mapping.put(‘9‘, "wxyz");
    }

    public List<String> letterCombinations(String digits) {
        List<String> res = new ArrayList<>();
        if (digits == null || digits.length() == 0) {
            return res;
        }
        combine(digits, "", res, digits.length());
        System.out.println(res);
        return res;
    }

    private void combine(String digits, String tmp, List<String> res, int length) {
        if (length == 0) {
            res.add(tmp);
            return;
        }
        for (int i = 0; i < digits.length(); i++) {
            String val = mapping.get(digits.charAt(i));
            if ("".equals(val)) {
                combine(digits.substring(i + 1), tmp, res, length - 1);
            } else {
                for (char c : val.toCharArray()) {
                    combine(digits.substring(i + 1), tmp + c, res, length - 1);
                }
            }
        }
    }


}

 

Letter Combinations of a Phone Number——LeetCode

标签:

原文地址:http://www.cnblogs.com/aboutblank/p/4395968.html

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