Letter combinations [1] [] leetcode-17 telephone numbers

Given a string contains only numeric characters 2-9, it can return all letter combinations indicated.

Given digital map to letters as follows (the same telephone key). Note 1 does not correspond to any alphabet.

 

 

Example:

Input: "23"
outputs:. [ "Ad", " ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
Description:
Although the above the answer is based on lexicographic order, but you can choose the order of the answer output.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/letter-combinations-of-a-phone-number

1. recursive add back

The input string digits.toCharArray () , to perform the current location i, res As a result of this backtracking parameter of backtrack

class Solution {
     List<String> result = new ArrayList<>();
     Map<Character, String> map = new HashMap<Character, String>(){{
        put('2', "abc");
        put('3', "def");
        put('4', "ghi");
        put('5', "jkl");
        put('6', "mno");
        put('7', "pqrs");
        put('8', "tuv");
        put('9', "wxyz");
    }};
    publicList <String> letterCombinations (String digits) {
          IF (digits.length () = 0! ) 
           BackTrack (digits.toCharArray (), 0, "" );
         return Result; 
    } 
     Private  void BackTrack ( char [] chars, int I , String RES) {
         IF (chars.length == I) { // I traversal has been completed are sequentially digital 
            result.add (RES); // the branch result is added List 
            return ; 
        } 
        String Letters = as map.get (chars [I]); // Get the number corresponding English composition 
        for ( int j = 0; j < letters.length(); j++) {
            String letter = letters.substring(j,j+1);
            backtrack(chars,i+1,res + letter);
        }

    }
    
}

 

2. Very sophisticated queue Solution

After the team plus each branch reentry team

public List<String> letterCombinations(String digits) {
        LinkedList<String> ans = new LinkedList<String>();
        if(digits.isEmpty()) return ans;
        String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        ans.add("");
        for(int i =0; i<digits.length();i++){
            int x = Character.getNumericValue(digits.charAt(i));
            while(ans.peek().length()==i){
                String t = ans.remove();
                for(char s : mapping[x].toCharArray())
                    ans.add(t+s);
            }
        }
        return ans;
    }

 

Guess you like

Origin www.cnblogs.com/twoheads/p/11272895.html