1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
| package algorithm;
import java.util.*;
public class Leetcode17 {
public static List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>(); String[] indexToStr = new String[]{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; if (digits == null || "".equals(digits)) return res; else if(digits.length() == 1) { char[] chars = indexToStr[Integer.parseInt(digits)].toCharArray(); for (int i = 0; i < chars.length; i++) { res.add(new String(new char[]{chars[i]})); } }
char[] charArray = digits.toCharArray(); char[] i0Char = indexToStr[(int) charArray[0] - (int) ('0')].toCharArray();
for (int i = 1; i < charArray.length; i++) {
for (int i1 = 0; i1 < i0Char.length; i1++) { char[] chars1 = indexToStr[(int) charArray[i] - (int) ('0')].toCharArray(); for (int i2 = 0; i2 < chars1.length; i2++) { res.add(new String(new char[]{i0Char[i1], chars1[i2]})); } }
} return res; }
Map<String, String> phone = new HashMap<String, 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"); }};
List<String> output = new ArrayList<String>();
public void backtrack(String combination, String next_digits) { if (next_digits.length() == 0) { output.add(combination); } else { String digit = next_digits.substring(0, 1); String letters = phone.get(digit); for (int i = 0; i < letters.length(); i++) { String letter = phone.get(digit).substring(i, i + 1); backtrack(combination + letter, next_digits.substring(1)); } } }
public List<String> letterCombinations1(String digits) { if (digits.length() != 0) backtrack("", digits); return output; }
public static void main(String[] args) { System.out.println(letterCombinations("3")); System.out.println(new Leetcode17().letterCombinations1("234")); } }
|