17. Letter Combinations of a Phone Number

2025. 4. 20. 12:50·Algorithm/LeetCode

문제

https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/

제한사항

풀이

    import java.util.*;

    class Solution {
        public List<String> letterCombinations(String digits) {
            
            Map<Character, List<String>> map = new HashMap<>();
            
            if(digits.equals("")) return new ArrayList<>();
            map.computeIfAbsent('2', k-> List.of("a", "b", "c"));
            map.computeIfAbsent('3', k-> List.of("d", "e", "f"));
            map.computeIfAbsent('4', k-> List.of("g", "h", "i"));
            map.computeIfAbsent('5', k-> List.of("j", "k", "l"));
            map.computeIfAbsent('6', k-> List.of("m", "n", "o"));
            map.computeIfAbsent('7', k-> List.of("p", "q", "r", "s"));
            map.computeIfAbsent('8', k-> List.of("t", "u", "v"));
            map.computeIfAbsent('9', k-> List.of("w", "x", "y", "z"));
            List<String> answer = new ArrayList<>();
            backtracking(map, digits, 0, new StringBuilder(), answer);

            return answer; 
        }

        private void backtracking(
            Map<Character,List<String>> map, String digits, int offset, StringBuilder comb,
            List<String> answer) {
                if(offset == digits.length()) {
                    answer.add(comb.toString());
                    return;
                }

                for(String l : map.get(digits.charAt(offset))) {
                    comb.append(l);
                    backtracking(map, digits, offset+1, comb, answer);
                    comb.deleteCharAt(comb.length()-1);
                }
        }
    }

회고

숫자에 여러 알파벳이 매칭되어 있다. 숫자 조합이 입력으로 주어지고 숫자 조합으로 만들 수 있는 모든 알파벳 조합을 구하는 문제였다. dfs를 활용하여 문제를 해결하였다. 

1. offset이 digits 길이가 되었을 때, answer에 알파벳 조합을 추가한다(add).

2. 알파벳 조합(comb)을 업데이트할 때, 다음 조합을 고려해서 backtracking이 끝나면, 추가했던 알파벳을 제거하는 작업을 포함한다.

for(String l : map.get(digits.charAt(offset))) {
                    comb.append(l);
                    backtracking(map, digits, offset+1, comb, answer);
                    comb.deleteCharAt(comb.length()-1);
                }

'Algorithm > LeetCode' 카테고리의 다른 글

403. Frog Jump  (0) 2025.04.04
[DP] 91. Decode Ways  (0) 2024.12.01
213. House Robber II  (0) 2024.11.30
377. Combination Sum IV  (0) 2024.11.17
1143. Longest Common Subsequence  (0) 2024.11.16
'Algorithm/LeetCode' 카테고리의 다른 글
  • 403. Frog Jump
  • [DP] 91. Decode Ways
  • 213. House Robber II
  • 377. Combination Sum IV
사랑우주인
사랑우주인
  • 사랑우주인
    lovelyAlien
    사랑우주인
  • 전체
    오늘
    어제
  • 글쓰기
    관리
    • 분류 전체보기 (209)
      • Programming (4)
        • Spring (28)
        • Java (46)
        • JPA (2)
        • 디자인 패턴 (5)
        • 개발&아키텍처 (0)
      • Network (14)
      • OS (19)
      • Database (1)
      • Kubernetes (0)
      • Kafka (2)
      • Algorithm (49)
        • BaekJoon (1)
        • Programmers (19)
        • Algorithm (5)
        • Socar (2)
        • LeetCode (19)
      • Interview (2)
      • Issues (2)
      • DotJoin (1)
      • Git (4)
      • 독서 (3)
      • 끄적끄적 (1)
      • 외부활동 (26)
        • 항해플러스 (2)
        • JSCODE 네트워크 (19)
        • JSCODE 자바 (5)
      • SQL (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • GitHub
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    트랜잭션
    wildcards
    OS
    Oauth2
    제네릭
    @JsonProperty
    운영체제
    BFS
    AuthenticationSuccessHandler
    Thread
    socar
    Generic
    RR
    LinkedList
    clone graph
    lower bounded wildcards
    fcfs
    @JsonNaming
    디자인 패턴
    준영속 엔티티
    Climbing Stairs
    rotting oranges
    Process
    minimum number of arrows to burst balloons
    pacific atlantic water flow
    JSCode
    Reorder List
    추상화 클래스
    runner 기법
    algorithm
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.1
사랑우주인
17. Letter Combinations of a Phone Number
상단으로

티스토리툴바