|
| 1 | +import java.util.ArrayList; |
| 2 | +import java.util.HashMap; |
| 3 | +import java.util.List; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +public class PhoneKeypadCombinations { |
| 7 | + public List<Stirng> phoneKeypadCombinations(String digits) { |
| 8 | + Map<Character, String> keypadMap = new HashMap<>(); |
| 9 | + keypadMap.put('2', "abc"); |
| 10 | + keypadMap.put('3', "def"); |
| 11 | + keypadMap.put('4', "ghi"); |
| 12 | + keypadMap.put('5', "jkl"); |
| 13 | + keypadMap.put('6', "mno"); |
| 14 | + keypadMap.put('7', "pqrs"); |
| 15 | + keypadMap.put('8', "tuv"); |
| 16 | + keypadMap.put('9', "wxyz"); |
| 17 | + List<String> result = new ArrayList<>(); |
| 18 | + backtrack(0, new ArrayList<>(), digits, keypadMap, result); |
| 19 | + return result; |
| 20 | + } |
| 21 | + |
| 22 | + private void backtrack(int i, List<Character> currCombination, String digits, Map<Character, String> keypadMap, List<String> result) { |
| 23 | + // Termination condition: if all digits have been considered, add the |
| 24 | + // current combination to the output list. |
| 25 | + if (currCombination.size() == digits.length()) { |
| 26 | + StringBuilder sb = new StringBuilder(); |
| 27 | + for (char c: currCombination) { |
| 28 | + sb.append(c); |
| 29 | + } |
| 30 | + result.add(sb.toString()); |
| 31 | + return; |
| 32 | + } |
| 33 | + for (char letter: keypadMap.get(digits.charAt(i)).toCharArray()) { |
| 34 | + // Add the current letter. |
| 35 | + currCombination.add(letter); |
| 36 | + // Recursively explore all paths that branch from this combination. |
| 37 | + backtrack(i + 1, currCombination, digits, keypadMap, result); |
| 38 | + // Backtrack by removing the letter we just added. |
| 39 | + currCombination.remove(currCombination.size() - 1); |
| 40 | + } |
| 41 | + } |
| 42 | +} |
0 commit comments