17. Alphabetic combinations of telephone numbers

Essentially a DFS, and then use StringBuilder instead of String in the process to reduce space consumption

Also pay attention to the handling of empty

  private String[] strings = {"abc"."def"."ghi"."jkl"."mno"."pqrs"."tuv"."wxyz"};

    public List<String> letterCombinations(String digits) {
        List<String> ans = new ArrayList<>();
        if (digits.length() == 0) return ans;
        dfs(digits, 0.new StringBuilder(), ans);
        return ans;

    }
    private void dfs(String digits, int index, StringBuilder builder, List<String> ans) {
        if (index == digits.length()) {
            ans.add(builder.toString());
            return;
        }
        String map = strings[digits.charAt(index) - '0' - 2];
        for (int i = 0; i < map.length(); i++) {
            StringBuilder sb = new StringBuilder(builder);
            sb.append(map.charAt(i));
            dfs(digits, index + 1, sb, ans); }}Copy the code