Letter Combinations of a Phone Number——LeetCode

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);

                }

            }

        }

    }





}

 

你可能感兴趣的:(LeetCode)