17. Letter Combinations of a Phone Number - Medium

前往題目

之前寫的文章

思路

  1. Map數字與字母
  2. backtracking,取到需要的數量就加到答案裡

Code

class Solution {
    private ArrayList<String> res;
    private Map<Character, String> digitToChar = Map.of(
        '2', "abc",
        '3', "def",
        '4', "ghi",
        '5', "jkl",
        '6', "mno",
        '7', "pqrs",
        '8', "tuv",
        '9', "wxyz"
    );
    public List<String> letterCombinations(String digits) {

        res = new ArrayList();

        if (!digits.isEmpty()){
            backtracking(0, "", digits);
        }

        return res;
    }

    private void backtracking(int i, String currStr, String digits) {
        // When string has built
        if (digits.length() == currStr.length()) {
            res.add(currStr);
            return;
        }

        String digit = digitToChar.get(digits.charAt(i));

        // Build the string
        for (char c : digit.toCharArray()) {
            backtracking(i + 1, currStr + c, digits);
        }

    }
}

17. Letter Combinations of a Phone Number - Medium
https://f88083.github.io/2024/04/08/17-Letter-Combinations-of-a-Phone-Number-Medium/
作者
Simon Lai
發布於
2024年4月8日
許可協議