From ab414c37a3465dc074efb215429b1173ae6a5a9a Mon Sep 17 00:00:00 2001 From: yennanliu Date: Tue, 3 Oct 2023 18:48:21 +0800 Subject: [PATCH] fix 017 java --- .../LetterCombinationsOfAPhoneNumber.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/leetcode_java/src/main/java/LeetCodeJava/BackTrack/LetterCombinationsOfAPhoneNumber.java b/leetcode_java/src/main/java/LeetCodeJava/BackTrack/LetterCombinationsOfAPhoneNumber.java index 203e3c5a..5e3edcf0 100644 --- a/leetcode_java/src/main/java/LeetCodeJava/BackTrack/LetterCombinationsOfAPhoneNumber.java +++ b/leetcode_java/src/main/java/LeetCodeJava/BackTrack/LetterCombinationsOfAPhoneNumber.java @@ -9,6 +9,49 @@ public class LetterCombinationsOfAPhoneNumber { + // V0 + List _res = new ArrayList(); + public List letterCombinations(String _digits) { + + if (_digits.length() == 0){ + return new ArrayList<>(); + } + + HashMap letters = new HashMap<>(); + letters.put("2", "abc"); + letters.put("3", "def"); + letters.put("4", "ghi"); + letters.put("5", "jkl"); + letters.put("6", "mno"); + letters.put("7", "pqrs"); + letters.put("8", "tuv"); + letters.put("9", "wxyz"); + + _letter_builder(letters, 0, _digits, new StringBuilder()); + return this._res; + } + + private void _letter_builder(HashMap map, int idx, String digits, StringBuilder builder){ + + if (builder.length() == digits.length()){ + this._res.add(builder.toString()); // NOTE this + return; + } + + String _digit = String.valueOf(digits.toCharArray()[idx]); // NOTE this + String _alphabets = map.get(_digit); + + // backtrack + for (char a : _alphabets.toCharArray()){ + builder.append(a); + _letter_builder(map, idx+1, digits, builder); + // undo + // builder.deleteCharAt(0); // NOTE !!! in backtrack, we remove LAST element (idx = len - 1), instead of first element + builder.deleteCharAt(builder.toString().length() - 1); + } + } + + // V0 // IDEA : BACKTRACK // public List letterCombinations(String digits) {